考虑此元素(出于问题的目的最小(:
class MyCountDown extends Polymer.Element
{
static get is () { return 'my-count-down'; }
static get properties ()
{
return {
time: { /* time in seconds */
type: Number,
observer: '_startCountDown'
},
remains: Number
}
}
_startCountDown ()
{
this.remains = this.time;
this.tickInterval = window.setInterval(() => {
this.remains--;
if (this.remains == 0) {
console.log('countdown!');
this._stopCountDown();
}
}, 1000);
}
_stopCountDown () {
if (this.tickInterval) {
window.clearInterval(this.tickInterval);
}
}
}
customElements.define(MyCountDown.is, MyCountDown);
如果我得到一个实例并设置属性 time ,
let MyCountDown = customElements.get('my-count-down');
let cd = new MyCountDown();
cd.time = 5;
属性 time 更改,但是观察者和 _startCountDown((函数未调用。我相信 polymer 正在等待该实例附加到DOM上,因为实际上,当我附加child((此元素时,计数开始启动,5秒钟后,控制台按预期登录'countdown!'
。/p>
我的目标是执行此生命周期而不将任何内容都附加到文档中,因为Mycountdown的实例并不总是附加到视图上,而是需要在我的Web应用程序的不同组件之间进行实时代码。
一种解决方案是将新的mycountdown实例附加到DOM的隐藏元素上,以强迫聚合物生命周期,但我认为这不是直觉。
我不知道确切的呼叫场所,但是您遇到的问题是属性评估者没有到位。
我认为您可能会从此谈话中获得线索
在构造函数回调中调用this._enableProperties()
?