代码之家  ›  专栏  ›  技术社区  ›  mcv

如何解耦Web组件?

  •  4
  • mcv  · 技术社区  · 7 年前

    我正在尝试使用纯javascript Web组件进行无框架工作。我希望我的Web组件能够独立工作并在不同的网站上使用,但我也希望两个组件能够进行通信。因此,它们应该能够在不紧密耦合的情况下进行通信。

    当我做棱角的时候,这很容易。我可以通过HTML属性将对象传递给组件,组件将其作为对象而不是字符串接收。但在纯javascript中,属性总是字符串。传递对象的正确方法是什么,或者以其他方式使Web组件相互感知并能够通信?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Supersharp    7 年前

    使用Web组件,您可以像您所说的那样通过属性传递对象,但也可以通过方法或属性(实际上是setter方法)传递对象。

    <my-component id="comp1"></my-component>
    ...
    var myObject = { y:1, y:2 }
    comp1.value = myObject     //via property
    comp1.setValue( myObject ) //via method
    
        2
  •  3
  •   Intervalia    7 年前

    下面是一个带有两个本机V1 Web组件的示例应用程序。 <component-1> 可以与对话 <component-2> 因为你提供了一个ID到 <组件1> 该ID指的是设置在 <组件2> .

    这与 <label> 使用its标记工作 for

    HTML

    <component-1 link-id="c2"></component-1>
    <hr/>
    <component-2 id="c2"></component-2>
    

    JS公司

    // Class for `<component-1>`
    class Component1 extends HTMLElement {
      constructor() {
        super();
        this._linkedComponent = null;
        this._input = document.createElement('input');
        this._input.addEventListener('focus', this._focusHandler.bind(this));
    
        this._button = document.createElement('button');
        this._button.textContent = 'Add';
        this._button.addEventListener('click', this._clickHandler.bind(this));
      }
    
      connectedCallback() {
        this.appendChild(this._input);
        this.appendChild(this._button);
      }
    
      static get observedAttributes() {
        return ['link-id'];
      }
    
      attributeChangedCallback(attrName, oldVal, newVal) {
        if (oldVal !== newVal) {
          if (newVal === null) {
            this._linkedComponent = null;
          }
          else {
            this._linkedComponent = document.getElementById(newVal);
          }
        }
      }
    
      _clickHandler() {
        if (this._linkedComponent) {
          this._linkedComponent.value = this._input.value;
        }
      }
    
      _focusHandler() {
        this._input.value = '';
      }
    }
    
    // Class for `<component-2>`
    class Component2 extends HTMLElement {
      constructor() {
        super();
        this._textArea = document.createElement('textarea');
        this._textArea.setAttribute('style','width:100%;height:200px;');
      }
    
      connectedCallback() {
        this.appendChild(this._textArea);
      }
    
      set value(newValue) {
        this._textArea.value += (newValue+'\n');
      }
    }
    
    customElements.define('component-1', Component1);
    customElements.define('component-2', Component2);
    

    <组件1> 只会与 <组件2> 如果有一个ID为的组件提供给 <组件1> 通过its link-id 属性

    推荐文章