将普通的脏标志与 css 绑定结合起来。
ko.dirtyFlag = function(root) {
var result = function() {}, // A function will not get serialized to JSON
_initialState = ko.observable(ko.toJSON(root));
result.isDirty = ko.dependentObservable(function() {
return _initialState() !== ko.toJSON(root);
});
result.reset = function() {
_initialState(ko.toJSON(root));
};
return result;
};
function ViewModel() {
// Normal properties
this.someProperty = ko.observable("initial value");
// Dirty-flag for this object.
this.dirtyFlag = ko.dirtyFlag(this);
}
<div data-bind="css: { 'new_class': dirtyFlag.isDirty }"></div>
如果您只想跟踪属性的子集,也可以传递一个可观察对象或可观察对象数组。
this.dirtyFlag = ko.dirtyFlag(this.someProperty);
http://jsfiddle.net/MizardX/7esdy/