KnockoutJS - How to exclude an observable from a computed observable

I computed an observable that uses ko.toJS () to publish values ​​(internal observables) from a view model. One of the internal observables is associated with a text box. How can I prohibit making changes to the text box from automatically starting the calculated observable (i.e., Postback)?

function viewModel() { var self = this; self.SearchParams = { OrderStatusID: ko.observable(), OrderNumber: ko.observable(), // I don't want this observable to trigger the postback OrderBy: ko.observable(), OrderByDirection: ko.observable(), PageIndex: ko.observable(), PageSize: ko.observable() }; // This computed observable automatically subscribes to every // observable in self.SearchParams. How can I ignore changes to // self.SearchParams.OrderNumber? ko.computed(function () { NS.post({ url: '/SomeUrl', data: ko.toJS(self.SearchParams) }); }).extend({ throttle: 1 }); } 
+4
source share
2 answers

Knockout 2.2+ includes a peek function to access observables without subscription. So you can do the following:

 ko.computed(function () { var s = self.SearchParams; NS.post({ url: '/SomeUrl', data: { OrderStatusID: s.OrderStatusID(), OrderNumber: s.OrderNumber.peek(), OrderBy: s.OrderBy(), OrderByDirection: s.OrderByDirection(), PageIndex: s.PageIndex(), PageSize: s.PageSize() } }); }).extend({ throttle: 1 }); 

If you're stuck in Knockout 2.1.0, you can increase your visibility manually by adding peek like this (thanks Ryan Niemeyer):

 var backdoorObservable = function(initialValue) { var _value = initialValue, result = ko.observable(initialValue); result.peek = function() { return _value; }; result.subscribe(function(newValue) { _value = newValue; }); return result; }; 

And then use backdoorObservable for OrderNumber :

 OrderNumber: backdoorObservable() 
+14
source

I wrote this little plugin to help me in many similar situations:

https://github.com/ZiadJ/knockoutjs-reactor

To ignore specific fields, it provides you with a hide parameter, which you can use like this:

 ko.watch(SearchParams, { hide: [SearchParams.OrderNumber] }, function () { NS.post({ url: '/SomeUrl', data: ko.toJS(SearchParams) }); }).extend({ throttle: 1 }); 
0
source

All Articles