Search code examples
javascriptknockout.jsknockout-mapping-pluginkolite

Knockoutjs track changes after ajax call


See JsFiddle here http://jsfiddle.net/WtgbV/2/

In words: I have some ajax call, and in the server's response I get some array of items (Items in knockout viewmodel)

I need to know that property name was changed in element with id==2 etc to save changes automatically on server (via POST request)

What is the simplest/easiest way to track changes in each element in Items array?


Solution

  • I co-wrote a component called DirtyFlag that detects changes in Knockout observables (or a set of them). You can grab in from my library called KoLite that you can grab off NuGet or GitHub.

    https://github.com/CodeSeven/KoLite

    https://nuget.org/packages/KoLite

    dirtyFlag

    // Your model
    var Person = function () {
        var self = this;
        self.id = ko.observable();
        self.firstName = ko.observable().extend({ required: true });
        self.lastName = ko.observable().extend({ required: true });
        self.dirtyFlag = new ko.DirtyFlag([self.firstName,self.lastName]);
        return self;
    };
    

    Hook these into your viewmodel to detect if there were changes ...

    //Property on your view model. myPerson is an instance of Person.
    //Did it Change?
    isDirty = ko.computed(function () {
        return myPerson().dirtyFlag().isDirty();
    }),
    

    Then to resync the changes ...

    //Resync Changes
    dirtyFlag().reset();