简体   繁体   中英

How to make 'independent' computed observable of some observable (Knockout.js)

I have three observables

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

and I need them all in computed observable

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

How to make co to update only if updates b or c ?
http://jsfiddle.net/DgVCF/

You can use the peek() function to get a 's value without creating a dependency on it in your computed:

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

See also in the documentation .

Demo JSFiddle .

Seems more as a job for subscribing

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM