Last active
December 17, 2015 02:38
-
-
Save benmccormick/5537138 to your computer and use it in GitHub Desktop.
Protected Observables by Ryan Niemeyer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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