How do you decouple Web Components?

前端 未结 2 2025
野趣味
野趣味 2021-01-20 00:13

I\'m trying to work frameworkless, with pure javascript Web Components. I want my Web Components to be able to work stand-alone and be used on different sites, and yet I als

2条回答
  •  长情又很酷
    2021-01-20 00:39

    Here is a sample app with two native V1 Web Components. can talk to because you supply an ID into and that ID refers to the ID set on .

    This is similar to how the tag work with its for attribute.

    HTML

    
    

    JS

    // Class for ``
    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 ``
    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);
    

    will only talk to if there is a component with the ID that was provided to through its link-id attribute.

提交回复
热议问题