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