我正在创建一个ko.computedObservable
:
var holder = ko.observable();
var makeAjax = function(){
holder('new value');
};
var result = ko.computed({
read: function () {
makeAjax();
return holder();
},
write: function (newValue) {
//not relevant
},
deferEvaluation: true
});
我希望能够subscribe
到result
而不会导致read
函数执行。
result.subscribe(function(val){
console.log(val);
});
但是,对订阅的调用导致read
执行。有没有办法订阅而不会导致它执行?
答案 0 :(得分:1)
您使用的是什么版本的Knockout?我无法重新创建此行为。这是我使用KO 3.0在JSbin上运行的代码片段并运行它不会导致结果读取函数进行评估,直到您调用getResult()
var vm = function() {
var holder = ko.observable();
var makeAjax = function() {
holder('new value');
};
var result = ko.computed({
read: function() {
console.log('excuting read')
makeAjax();
return holder();
},
write: function(newValue) {
console.log('setting holder to ' + newValue)
//not relevant
holder(newValue)
},
deferEvaluation: true
});
result.subscribe(function(val) {
console.log(val);
});
this.getResult = function() {
return result;
}
this.setResult = function(val) {
result(val);
}
}
var VM = new vm();
ko.applyBindings(VM);
VM.setResult("test");