Javascript 属性更改未在双向数据绑定聚合上被激发
在我的聚合物元素中,我使用了属性更改方法Javascript 属性更改未在双向数据绑定聚合上被激发,javascript,polymer,2-way-object-databinding,Javascript,Polymer,2 Way Object Databinding,在我的聚合物元素中,我使用了属性更改方法 Polymer('my-tag', { //some code attributeChanged: function(attrName, oldVal, newVal) { console.log(attrName, 'old: ' + oldVal, 'new:', newVal); }, myAttributeChanged: function(oldVal, newVal){ console.log("myattri
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";
//在脚本部分
this.wowAttribute=“哇”;
这不会调用attributeChanged
方法,而只调用myAttributeChanged
这是预期的行为吗?有没有办法获得为双向数据绑定调用的空白更改方法?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;
}
}
}
}
所以基本上,对于任何以“改变”结尾的性质,聚合物都会为“改变”的结果建立一个观察者。有趣的是,这实际上不必是聚合物元素中任何地方定义的属性,但这是另一回事 谢谢。所以唯一的方法就是设置观察者的所有属性,对吗?好吧,你可以使用setAttribute,但必须有另一种方法。我要挖一些