Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs: how to get notications for all the properties an once

Tags:

knockout.js

Suppose I have a ViewModel with 100 props. Currently I need a one handler that will be called if any of the props changes. Of course I can write 100 .subscribe for every property, but it seems, that there is a better way. Like in C#, where you can bind to PropertyChanged event of the model, and then choose properties of interest by their names.

like image 388
Vladimir Perevalov Avatar asked Oct 21 '11 13:10

Vladimir Perevalov


People also ask

Can we have multiple Knockout models on a single page?

Knockout now supports multiple model binding. The ko. applyBindings() method takes an optional parameter - the element and its descendants to which the binding will be activated. This restricts the activation to the element with ID someElementId and its descendants.

What is Purecomputed in Knockout?

Pure computed observables, introduced in Knockout 3.2. 0, provide performance and memory benefits over regular computed observables for most applications. This is because a pure computed observable doesn't maintain subscriptions to its dependencies when it has no subscribers itself.

What is $data in Knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

What is applyBindings in Knockout?

applyBindings do, The first parameter says what view model object you want to use with the declarative bindings it activates. Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.


2 Answers

The general answer is to create a dependentObservable that subscribes to everything. This can be easily accomplished by doing a ko.toJS(viewModel) inside of a dependentObservable, as it will recursively unwrap all observables. You will want to take caution to not include yourself in the ko.toJS call or you can get into an infinite loop.

If you are looking for something with a little more functionality, then take a look at this post.

like image 174
RP Niemeyer Avatar answered Oct 11 '22 23:10

RP Niemeyer


I think you're using KO 1.2.1. It is not so easy in this version. However Knockout 1.3 is coming. Currently it is beta but it is pretty stable. Throttling has been implemented in Knockout 1.3. I think this is what you need.

You could read more about 1.3 version here: http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/

And examine on-line sample: http://jsfiddle.net/StevenSanderson/Rnmb2/1/

Probably I could help you with implementation in case you need some assistance.

I hope it is exactly what you need.

like image 38
Romanych Avatar answered Oct 12 '22 00:10

Romanych