簡體   English   中英

attributeChanged不會在2向數據綁定聚合物上觸發

[英]attributeChanged not getting fired on 2 way data binding polymer

在我的聚合物元素中,我有attributeChanged方法

Polymer('my-tag', {
  //some code
  attributeChanged: function(attrName, oldVal, newVal) {
    console.log(attrName, 'old: ' + oldVal, 'new:', newVal);
  },
  myAttributeChanged: function(oldVal, newVal){
    console.log("myattribute changed", 'old: ' + oldVal, 'new:', newVal);
  }
});

當我手動更改屬性時,將調用此方法。

tag.setAttribute('myAttribute',"wow");

當我通過2方式數據綁定設置屬性時,這不會被調用

 <my-tag id="myTagId" myAttribute="{{wowAtrribute}}"></my-tag>
//in script section
this.wowAttribute = "wow";

這不會調用attributeChanged方法,而只是調用myAttributeChanged

這是預期的行為嗎? 有沒有辦法為2種方式的數據綁定調用空白的Changed方法?

TLDR:深入研究poylmer.js和CustomElements.js,您所看到的確實是應該如何執行的(可能不是它們的意圖,至少是在代碼中)。

在CustomElements.js中,有這兩個對函數進行重載,它們一起重載setAttribute和removeAttribute函數,以調用changeAttributeCallback函數。

  function overrideAttributeApi(prototype) {
    if (prototype.setAttribute._polyfilled) {
      return;
    }
    var setAttribute = prototype.setAttribute;
    prototype.setAttribute = function(name, value) {
      changeAttribute.call(this, name, value, setAttribute);
    };
    var removeAttribute = prototype.removeAttribute;
    prototype.removeAttribute = function(name) {
      changeAttribute.call(this, name, null, removeAttribute);
    };
    prototype.setAttribute._polyfilled = true;
  }
  function changeAttribute(name, value, operation) {
    name = name.toLowerCase();
    var oldValue = this.getAttribute(name);
    operation.apply(this, arguments);
    var newValue = this.getAttribute(name);
    if (this.attributeChangedCallback && newValue !== oldValue) {
      this.attributeChangedCallback(name, oldValue, newValue);
    }
  }

在polymer.js中,“ attributeChanged”實際上被別名為“ attributeChanged”。 因此,只有在使用setAttribute或removeAttribute時才使用回調。

對於單個屬性,雖然有所不同。 在polymer.js中,這是設置“ myAttributeChanged”功能的地方

  inferObservers: function(prototype) {
      // called before prototype.observe is chained to inherited object
      var observe = prototype.observe, property;
      for (var n in prototype) {
        if (n.slice(-7) === 'Changed') {
          property = n.slice(0, -7);
          if (this.canObserveProperty(property)) {
            if (!observe) {
              observe  = (prototype.observe = {});
            }
            observe[property] = observe[property] || n;
          }
        }
      }
    } 

因此,基本上,對於以“ Changed”結尾的任何屬性,聚合物都會為“ Changed”收益設置觀察者。 有趣的是,實際上並不一定要在聚合物元素中的任何位置定義一個屬性即可起作用,但這是另一回事。

暫無
暫無

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

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