From 200045a0dbc3d292350f4944d5fcfa2a21680d20 Mon Sep 17 00:00:00 2001 From: nenitiko Date: Sun, 20 Oct 2013 03:37:46 -0400 Subject: [PATCH] Update knockout.dirtiable.js This is actually a mixed-up version of Ryan's and Areson's work. From Ryan's implementation I took the dirty-able functionality from you I took the interface, the extender and the initiative. One of the problems I found with your implementation was that once an object was made dirty there was no turning back, it stayed dirty even when changing all properties to their initial values, for example if you track an Array and add an item, it is marked was dirty but if you removed that same item, it wont go back to non-dirty state. Ryan's work supports that. --- knockout.dirtiable.js | 41 +++++++++++++---------------------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/knockout.dirtiable.js b/knockout.dirtiable.js index 91b5b23..73eb3ba 100644 --- a/knockout.dirtiable.js +++ b/knockout.dirtiable.js @@ -2,33 +2,18 @@ * based on the the work done by Ryan Niemeyer. * (http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html) */ -ko.extenders.dirtiable = function(target) { - var _dirty = {}; - _dirty.isDirty = ko.observable(false); - _dirty.initialState = null; - _dirty.tracker = ko.computed(function() { - if(!_dirty.isDirty()) - ko.toJSON(target); - - return(_dirty.isDirty()); +ko.extenders.dirtiable = function (target) { + var _initialState = ko.observable(ko.toJSON(target)), + _isInitiallyDirty = ko.observable(false); + + target.dirty = ko.computed(function () { + return _isInitiallyDirty() || _initialState() !== ko.toJSON(target); }); - - //Track changes to observable - _dirty.tracker.subscribe(function() { - if(!_dirty.isDirty() && _dirty.initialState !== ko.toJSON(target)) - _dirty.isDirty(true); - }); - - //Create the dirty flag on the observable - target.dirty = ko.computed(function() { - return(_dirty.isDirty()); - }); - - //Allow users to reset the dirty flag - target.clean = function() { - _dirty.initialState = ko.toJSON(target); - _dirty.isDirty(false); - } - + + target.clean = function () { + _initialState(ko.toJSON(target)); + _isInitiallyDirty(false); + }; + return target; -} \ No newline at end of file +};