开发者

knockout subscribe to observables needed?

开发者 https://www.devze.com 2023-03-14 01:48 出处:网络
I have a form with four input fields. I need to update the res (3) when one is updated from the UI. Meaning the one that is updated could be any of the four.

I have a form with four input fields. I need to update the res (3) when one is updated from the UI. Meaning the one that is updated could be any of the four.

myViewModel.four.subscribe(function(newValue) {

//update one here
//update two here
//update three here

}); 

and so on.....

myViewModel.one.subscribe(function(newValue) {


//update two here
//update three here
//update four here

}); 

but how should I update the ones inside the method? To me it would look like a Stac开发者_如何转开发k Overflow situation...


In Knockout 1.2.1, if an observable is updated with exactly the same value, then updates will not be sent out. So, in that case you should be okay, if each of the values is updated with the same value.

Previously though, the best way to avoid a recursive loop of updates is to check in your subscribe if the observable really needs to be updated. This will cut the chain of updates.

So:

myViewModel.one.subscribe(function(newValue) {

    if (two() !== "the right value") {
       two("the right value");
    }
    //etc...
}); 

Otherwise, if there is more to your scenario, then there may be other options with writable dependentObservables that could be explored. When you get more than a two-way relationship though, manual subscriptions are usually the best bet.

0

精彩评论

暂无评论...
验证码 换一张
取 消