因此,我试图使某些Polymer数据绑定正常工作,但由于某些原因,以下代码给了我一个 TypeError: this.setAttribute is not a function(…)
我尝试用替换this.setAttribute('display', 1);
,this.display = 1;
但似乎也不起作用。
我究竟做错了什么?
Polymer({
is: 'unibz-club',
properties: {
display:{
type: Number,
notify: true,
value: 0,
}
},
ready: function() {
this.setAttribute('display', 1); // <--not working
}.bind(this),
};
“就绪”方法已经具有一个this
上下文,该上下文引用要实例化的Polymer对象。现在,您正在将上下文更改为窗口或包含.bind(this)
调用的闭包。
Polymer库正在为您处理此问题。它将在新创建的对象的上下文中调用“ ready”方法。
通常,您将.bind()
用于定义this
in回调方法和then-promise的上下文。当然还有其他用途,但这在我的经验中是最常见的。
function ImageLoader () {
return this;
}
ImageLoader.prototype.load = function(path) {
return ajaxService.get(path);
};
function Gallery () {
this.images = [];
return this;
}
Gallery.prototype.init = function() {
new ImageLoader().load('/photos/gallery').then(function(result) {
this.images = result;
}.bind(this)); // <-- .bind(this) will set the context of `this` to the Gallery instance
};
var gallery = new Gallery();
gallery.init();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句