问题
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?
回答1:
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();
回答2:
Knockout has a built in PubSub system (used by their observables and other core elements).
You could make use of this system by extending each of your properties to publish an event on a certain topic after being edited.
You'd then need to have a subscription on this topic so you can track changes in the data.
Take a look at this excellent post
You can easily achieve this by providing your own mapping. The following is a very basic example, just to show you what the PubSub system could do for you. See example.
If I may give you a hint, it's might be a better idea to not save per property but to detect changes and do an autosave of the whole array after a certain period.
So each value will publish a 'change event' on the topic and each time you receive a message on a topic the timeOut will be reset. After timeout expires you can save changes in the BE.
来源:https://stackoverflow.com/questions/12422708/knockoutjs-track-changes-after-ajax-call