Knockout.js 敲除可写的计算观察值,创建计时器
我试图在knockoutjs中创建一个可写的可计算的可观察对象,我几乎完成了,但它无法读取计算值。我做错什么了吗Knockout.js 敲除可写的计算观察值,创建计时器,knockout.js,Knockout.js,我试图在knockoutjs中创建一个可写的可计算的可观察对象,我几乎完成了,但它无法读取计算值。我做错什么了吗 this.time_remaining = ko.computed({ read: function() { return this.time_remaining; <!-- Does this need setInterval? --> }, write: function() { window.setInterv
this.time_remaining = ko.computed({
read: function() {
return this.time_remaining; <!-- Does this need setInterval? -->
},
write: function() {
window.setInterval(function() {
this.time_remaining = moment('2015-09-14').countdown().toString();
console.log(this.time_remaining)
<!-- The console shows a timer, that is exciting! -->
}, 1000)
},
owner: this
});
this.time_剩余=ko.computed({
读:函数(){
返回此。剩余的时间;
},
写入:函数(){
setInterval(函数(){
这个.time_剩余=时刻('2015-09-14')。倒计时();
console.log(剩余时间)
}, 1000)
},
业主:这个
});
但是,它仍然无法读取数据绑定中的值,并且无法正常工作。也许我完全错了
<h4 data-bind="text: time_remaining" class="timer"></h4>
您需要一个支持变量来进行计算
this.time;
this.time_remaining = ko.computed({
read: function() {
return this.time;
}
});
你不需要一个可写的计时器。您只需更改间隔上的常规观测值:
var ViewModel=函数(倒计时){
var self=这个;
self.time_剩余=ko.observable();
var updateCountdown=函数(){
var diff=时刻持续时间(倒数计时到时刻());
var textDiff=diff.hours()+“:”+diff.minutes()+“:”+diff.seconds();
自身剩余时间(textDiff);
};
设置间隔(updateCountdown,1000);
updateCountdown();
};
var-then=moment()。添加(10,'h');//假装!
应用绑定(新视图模型(then))代码>
需要另一个属性作为支持变量。现在,看起来您正在将computed作为值返回,而write正在覆盖computed。