attributeChanged没有被2路数据绑定聚合物触发

时间:2015-04-20 10:19:15

标签: javascript polymer 2-way-object-databinding

在我的聚合物元素中,我有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");

当我通过双向数据绑定设置属性

时,不会调用此方法
 <my-tag id="myTagId" myAttribute="{{wowAtrribute}}"></my-tag>
//in script section
this.wowAttribute = "wow";

这不会调用attributeChanged方法,只需调用myAttributeChanged

这是预期的行为吗?有没有办法为双向数据绑定调用一个空白的Changed方法?

1 个答案:

答案 0 :(得分:2)

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&#39; attributeChanged&#39;是有效的别名为&#39; attributeChanged&#39;。因此,使用回调的唯一时间是使用setAttribute或removeAttribute。

虽然个别属性有所不同。在polymer.js中,这就是那些“我的属性变化”的地方。功能已设置

  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;
          }
        }
      }
    } 

所以基本上,对于任何结束于&#34;更改&#34;聚合物为任何收益建立观察者&#34;变更&#34;。有趣的是,这实际上不一定是聚合物元素中任何地方定义的属性,但这是一个不同的故事。