Skip to content

Instantly share code, notes, and snippets.

@benmccormick
Last active December 17, 2015 02:38
Show Gist options
  • Save benmccormick/5537138 to your computer and use it in GitHub Desktop.
Save benmccormick/5537138 to your computer and use it in GitHub Desktop.
Protected Observables by Ryan Niemeyer
/* Small Knockout Extension to allow for canceling/confirming
* changes to the view model Originally from:
* http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html
*/
//wrapper to an observable that requires accept/cancel
ko.protectedObservable = function(initialValue) {
//private variables
var _actualValue = ko.observable(initialValue),
_tempValue = initialValue;
//computed observable that we will return
var result = ko.computed({
//always return the actual value
read: function() {
return _actualValue();
},
//stored in a temporary spot until commit
write: function(newValue) {
_tempValue = newValue;
}
});
//if different, commit temp value
result.commit = function() {
if (_tempValue !== _actualValue()) {
_actualValue(_tempValue);
}
};
//force subscribers to take original
result.reset = function() {
_actualValue.valueHasMutated();
_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