This is probably one of my favorite data bindings for Knockout.js: isdirty. The concept behind the function is to track when there is a change to any object including any of its properties. It’s extremely powerful handling nested objects as well.
Let’s take a look at how to use:
[code]
var customer = {
“firstName”: ko.observable(“End your”),
“lastName”: ko.observable(“If”)
};
customer.dirtyFlag = new ko.dirtyFlag(customer);
[/code]
The above code initializes a customer object with two parameters: first and last name. Both of these properties are defined as observables. When a change happens to either property, the following property on the customer object will return true: customer.dirtyFlag.isDirty()
You can apply logic to this computed observable to identify data on your page has changed.
And finally let’s look at the actual code behind the function:
[code]
ko.dirtyFlag = function (root, isInitiallyDirty) {
var result = function () { },
_initialState = ko.observable(ko.toJSON(root)),
_isInitiallyDirty = ko.observable(isInitiallyDirty);
result.isDirty = ko.computed(function () {
return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
});
result.reset = function () {
_initialState(ko.toJSON(root));
_isInitiallyDirty(false);
};
return result;
};
[/code]