0

在我的聚合物元素中,我有 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 方法?

4

1 回答 1

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 中,“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”的任何进展设置一个观察者。有趣的是,这实际上不必是在聚合物元素的任何地方定义的属性才能起作用,但这是另一回事。

于 2015-04-20T19:42:47.347 回答