简体   繁体   中英

Explicitly subscribe a computed to an observable

In the following code, is there a way to explicitly subscribe comp to b , so that clicking change a and then change b would always fire comp (regardless how much times change a is clicked before change b )?

[Note that I'm not looking for a solution like taking self.b() out of the else block (or other similiar tricks), but rather an explicit call to some function, I guess something similiar to subscribe ]

 var ViewModel = function () { var self = this; self.a = ko.observable(true); self.b = ko.observable(1); self.changeA = function () { console.log("changeA clicked"); self.a(!self.a()); } self.changeB = function () { console.log("changeB clicked"); self.b(0); } self.comp = ko.computed(function () { if (!self.a()) { console.log("a"); // ... some code that computes a ... } else { console.log("b"); var b = self.b(); // ... some code that computes b ... } return "hello"; }) } vm = new ViewModel(); ko.applyBindings(vm); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <button data-bind="click: changeA, text: 'change a'"></button> <button data-bind="click: changeB, text: 'change b'"></button> 

Is there anything wrong with using a subscriber and another observable?

 var ViewModel = function() { var self = this; self.a = ko.observable(true); self.b = ko.observable(1); self.changeA = function() { self.a(!self.a()); } self.changeB = function() { self.b(0); } self.comp = ko.observable(); self.b.subscribe(function(newVal) { console.log('b was changed to ', newVal); self.comp(newVal); }) } vm = new ViewModel(); ko.applyBindings(vm); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <button data-bind="click: changeA, text: 'change a'"></button> <button data-bind="click: changeB, text: 'change b'"></button> 

@Roy J was right in his comments: The given code is a good sign for trying to do something the wrong way. I'll leave this question as a warning sign.

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