Detecting change to Knockout view model

user1389723 picture user1389723 · May 16, 2012 · Viewed 47.7k times · Source

Sure this is a very easy question to answer but is there an easy way to determine if any property of a knockout view model has changed?

Answer

Brett Green picture Brett Green · Jul 13, 2012

Use extenders:

ko.extenders.trackChange = function (target, track) {
    if (track) {
        target.isDirty = ko.observable(false);
        target.originalValue = target();
        target.setOriginalValue = function(startingValue) {
            target.originalValue = startingValue; 
        };
        target.subscribe(function (newValue) {
            // use != not !== so numbers will equate naturally
            target.isDirty(newValue != target.originalValue);
        });
    }
    return target;
};

Then:

self.MyProperty= ko.observable("Property Value").extend({ trackChange: true });

Now you can inspect like this:

self.MyProperty.isDirty()

You can also write some generic viewModel traversing to see if anything's changed:

self.isDirty = ko.computed(function () {
    for (key in self) {
        if (self.hasOwnProperty(key) && ko.isObservable(self[key]) && typeof self[key].isDirty === 'function' && self[key].isDirty()) {
            return true;
        }
    }
});

... and then just check at the viewModel level

self.isDirty()