Search code examples
knockout.jskolite

Is it possible to get original object values from koLite?


I'm using knockoutJS and koLite. It appears that koLite is somehow storing the original values of my object. I say that because if I edit a value, the dirty flag returns true. BUT, if I change that value back to its original value, dirty flag gets reset back to false.

So, if koLite is actually storing the original values of my object, is there a way to use that to restore my object to its original state? The idea here is an edit form where the user decides to cancel their changes.


Solution

  • Looking at the source of dirtyFlag, yes it keeps track of the original value, at least in as much as it's hashed the value (but the default "hash" function is actually just ko.toJSON, so it has the value available):

    _lastCleanState = ko.observable(hashFunction(_objectToTrack)),
    

    But there's no in-built mechanism to reset the value back to, or retrieve, it's original one - you'd have to write something yourself. If the hashing function ever changes, or a different one is provided to koLite, it may not even have the original value available, so don't depend on it being there in future versions.

    Reverting knockout view models (not necessarily in anyway related to koLite) has been discussed a few times on Stack Overflow already, so there may be an answer out there that doesn't use koLite to do the reversion. If done properly, koLite should update and set the dirty flag back to false.