knockoutjs: how to get notications for all the pro

2019-02-22 12:27发布

问题:

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.

回答1:

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.



回答2:

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.



标签: knockout.js