Ajax调用后Knockoutjs跟踪更改 [英] Knockoutjs track changes after ajax call
问题描述
在此处查看JsFiddle http://jsfiddle.net/WtgbV/2/
See JsFiddle here http://jsfiddle.net/WtgbV/2/
换句话说:我有一个ajax调用,并且在服务器的响应中,我得到了一些项目数组(敲除视图模型中的项目)
In words: I have some ajax call, and in the server's response I get some array of items (Items in knockout viewmodel)
我需要知道元素中的属性name
已用id==2
等更改,以便自动将更改保存在服务器上(通过POST请求)
I need to know that property name
was changed in element with id==2
etc to save changes automatically on server (via POST request)
跟踪Items
数组中每个元素的变化的最简单/最简单的方法是什么?
What is the simplest/easiest way to track changes in each element in Items
array?
推荐答案
我与他人共同编写了一个名为DirtyFlag的组件,该组件可检测Knockout可观察对象(或其中一组)的变化.您可以从我称为KoLite的库中获取,也可以从NuGet或GitHub中获取.
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();
这篇关于Ajax调用后Knockoutjs跟踪更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!