簡體   English   中英

為什么 Webcomponent 對象的值在同一個 webcomponent 的不同實例之間共享?

[英]Why does Webcomponent object value is shared between the different instances of the same webcomponent?

我使用 Polymer 創建了一個名為TestElement的 Web 組件,如下所示。 它只有一個對象值和一個向該組件添加值的函數。

<dom-module id="test-element">
  <template>Test Element</template>

  <script>
    class TestElement extends Polymer.Element {
    static get is() { return "test-element"; }

    static get properties() {
      return {
        _myVar: {
          type: Object,
          value: {},
        },
      };
    }

    addNew(key, val) {
      this._myVar[key] = val;
    }
  }

  customElements.define(TestElement.is, TestElement);
</script>
</dom-module>

我在父元素中創建了兩個實例,如下所示:

class ParentElement extends Polymer.Element {
  static get is() { return "parent-element"; }

  ready() {
    super.ready();
    this.$.myElement.addNew('key1', 'val-1');
    this.$.myElement2.addNew('key2', 'val2'); 
    console.log(this.$.myElement._myVar); // Expected to have {'key1': 'val-1'} but got {'key1': 'val-1', 'key2': 'val2'}. Why?
  }
}

在上面的控制台日志中,我希望有{'key1': 'val-1'}但得到{'key1': 'val-1', 'key2': 'val2'} 為什么?

如果你想有一個工作示例,請參考這個 plunkr:

http://plnkr.co/edit/7jSwTTBbBxD4qCbUoCGI?p=preview

JavaScript 對象是按引用的,當您定義默認值時,它是單個對象。

static get properties() {
  return {
    _myVar: {
      type: Object,
      value: {},
    },
  };
}

為了避免這種情況,您可以定義一個函數該函數將為每個組件實例返回一個新對象。

static get properties() {
  return {
    _myVar: {
      type: Object,
      value: function() { return {}; },
    },
  };
}

在思考的過程中,我找到了解決方案。

測試元素

class TestElement extends Polymer.Element { static get is() { return "test-element"; }

static get properties() {
  return {
    _myVar: {
      type: Object,
      value: {},
    },
  };
}

ready() {
  super();
  _myVar = {}; // if initialized like this, the objects are not shared anymore.
}

addNew(key, val) {
  this._myVar[key] = val;
}

}

customElements.define(TestElement.is, TestElement);

所以在下面,記錄我的預期:

class ParentElement extends Polymer.Element {
     static get is() { return "parent-element"; }

  ready() {
    super.ready();
    this.$.myElement.addNew('key1', 'val-1');
    this.$.myElement2.addNew('key2', 'val2'); 
    // Expected to have {'key1': 'val-1'} and got {'key1': 'val-1'} check! :)
    console.log(this.$.myElement._myVar); 
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM