如何使某些可观察的“独立”计算可观察量(Knockout.js)

时间:2013-11-16 20:16:49

标签: javascript knockout.js

我有三个可观察者

viewModel.a = ko.observable(0);
viewModel.b = ko.observable(0);
viewModel.c = ko.observable(0);

我在计算的可观察的

中需要它们
viewModel.co = ko.computed(function(){
    var a = this.a();
    return this.b() + this.c();
}, viewModel);

如果co更新bc,如何更新{{1}}? http://jsfiddle.net/DgVCF/

2 个答案:

答案 0 :(得分:3)

您可以使用peek()函数获取a的值,而不会在计算中创建对它的依赖:

viewModel.co = ko.computed(function(){
    var a = this.a.peek();
    console.log(1);
    return this.b() + this.c();
}, viewModel);

另见documentation

演示JSFiddle

答案 1 :(得分:0)

似乎更像是订阅

的工作
var viewModel = {};

viewModel.a = ko.observable(0);
viewModel.b = ko.observable(0);
viewModel.c = ko.observable(0);

viewModel.co = ko.observable(0);

viewModel.b.subscribe(function(newValue) {
    viewModel.co(parseInt(viewModel.b()) + parseInt(viewModel.c()));
});

viewModel.c.subscribe(function(newValue) {
    viewModel.co(parseInt(viewModel.b()) + parseInt(viewModel.c()));
});

ko.applyBindings(viewModel);