How to subscribe to any changes to a viewModel

658 views
Skip to first unread message

greengiant

unread,
May 1, 2011, 10:19:58 AM5/1/11
to KnockoutJS
I have a view model that is made up of several observable properties
and arrays, as well as sub objects that themselves are made up of
observable properties and arrays. Is there a way to subscribe to
change to any of these observables?

The reason I want to do this because I am making a report editor that
has a preview tab. Whenever something changes to the viewModel I
want
to reset the preview tab so that the report has to be rerun to be
viewed.

rpn

unread,
May 1, 2011, 11:27:38 AM5/1/11
to knock...@googlegroups.com
Hello-
One way to accomplish what you are after is to set up a dependentObservable that accesses all of the underlying observables.  The easy way to do this is to call ko.toJS(yourobject) from within the dependentObservable, as it will access all of the underlying observables.  You don't even need to do anything with the result of ko.toJS or bind to the dependentObservable.   Then, you can subscribe to changes to your dependentObservable and react any way that you choose.

Here is a sample: http://jsfiddle.net/rniemeyer/TTGbH/.  The sample is basic, but the idea would work though with observableArrays and nested observables.  

I am actually working on a blog post with ideas about creating a dirty flag that is a bit more sophisticated, but the underlying idea is the same.

greengiant

unread,
May 1, 2011, 12:20:28 PM5/1/11
to KnockoutJS
Thanks, rpn. That is a clever solution. I havent tested it yet, but I
would this work with changes to an item that is pushed into an
observable array after the initial definition of the allChanges
property?

rpn

unread,
May 1, 2011, 5:49:28 PM5/1/11
to knock...@googlegroups.com
As long as the observableArray (empty even) is defined before the dependentObservable, then it should work properly.
Reply all
Reply to author
Forward
0 new messages