Follow @endyourif rss Facebook LinkedIn

Knockout isdirty custom data binding Knockout isdirty custom data binding

Published on May 31, 2022

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:

var customer = {
"firstName": ko.observable("End your"),
"lastName": ko.observable("If")

customer.dirtyFlag = new ko.dirtyFlag(customer);

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:

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 () {




return result;


Tags: Knockout js Tutorial | JavaScript | isdirty | Knockout js Tutorial

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP