Skip to content

Instantly share code, notes, and snippets.

@benmccormick
Last active December 17, 2015 02:38
Show Gist options
  • Save benmccormick/5537115 to your computer and use it in GitHub Desktop.
Save benmccormick/5537115 to your computer and use it in GitHub Desktop.
Revertible Observable
/* Small Knockout Extension to allow for canceling/confirming
* changes to the view model. Defaults to the changed option. Based on code sample from Ryan Niemeier
* http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html
*
* Please note: You should not use this unless you are
* explicitly confirming or resetting the values in every scenario before you
* reference them again. An unwanted revert may occur if you make changes without confirming and then cancel at a later point.
*/
//wrapper to an observable that requires accept/cancel
ko.revertibleObservable = function(initialValue) {
//private variables
var _actualValue = initialValue,
_tempValue = ko.observable(initialValue);
//computed observable that we will return
var result = ko.computed({
//always return the current value
read: function() {
return _tempValue();
},
//stored in a temporary spot until commit
write: function(newValue) {
_tempValue(newValue);
}
});
//if different, commit temp value
result.commit = function() {
if (_tempValue() !== _actualValue) {
_tempValue.valueHasMutated();
_actualValue = _tempValue();
}
};
//force subscribers to take original
result.reset = function() {
_tempValue(_actualValue); //reset temp value
};
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment