Last Updated: February 25, 2016
·
5.75K
· rbj325

Easy Autosaving with Knockout.js Dirty Flag

Reduce the number of user interactions required on your pages by implementing auto saving via a dirty flag on your client side domain model.

This can be achieved using knockout.js:

window onload fuction:

//Handle dirty/changed domain items
templateAppViewModel.dirtyTemplates = ko.dependentObservable(function () {
return ko.utils.arrayFilter(this.templateResults(), 
function (template) { 
    return template.dirtyFlag.isDirty(); 
});}, templateAppViewModel);

//Create the view model dirty flag
templateAppViewModel.isDirty = ko.dependentObservable(function () {
    return this.dirtyTemplates().length > 0;
}, templateAppViewModel);

//subscribe to viewmodel isDirty event
templateAppViewModel.isDirty.subscribe(function (newValue) {
if (newValue) {        
    //Save the dirty values
    viewModelHelpers.save();
}
});


//Initialize Knockout.js
ko.applyBindings(templateAppViewModel);

Client Side Domain Object:

function Template(){
 this.dirtyFlag = new ko.dirtyFlag(this);
}

JS Fiddle: http://jsfiddle.net/rniemeyer/dtpfv/

Code and Idea from:
http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html