Changing Eventhandler model in knockout.js
I need to know (in JS) when my model (using knockout.js) or rather a property changed.
How to do it?
Here is the code:
function DrawingToolViewModel() {
var self = this;
self.drawMode = ko.observable('Line');
}
model = new DrawingToolViewModel();
ko.applyBindings(model);
Now the assigned HTML element for drawMode will be updated by the model and back, regardless of changes. This is fine, but how can I react in JS if something has changed in the model?
EDIT
My question was not clear enough, sorry. I know observables, but I want to subscribe to ALL properties without doing it for every single property. More like "notify me if something has changed in the model"
source to share
If you want to register your own subscriptions to be notified of changes to observables, you can call their subscription function, for example:
myViewModel.personName.subscribe(function(newValue) {
alert("The person new name is " + newValue);
});
More @ knockoutjs.com
Summarizing the comments below
To be notified of every change in the ViewModel, check Ryan Niemeyer and John papa changeTracker on NuGet
source to share
If you want to be notified when a specific property appears, there are several ways to do what you want. One way is to use a function subscribe
:
model.drawMode.subscribe(function(newValue) {
// your js goes in here
});
EDIT
However, if you want to be notified when ANY property changes appear in your view model, I would look at this post for creating a dirty flag:
http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html
This effectively tracks any changes in your viewmodel so you can tailor them to your needs.
source to share