Created
September 7, 2017 16:02
-
-
Save KeesCBakker/0f732550f95c327545d7cca7a919d319 to your computer and use it in GitHub Desktop.
Knockout JS Conditioned Observable
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
"use strict"; | |
ko.conditionedObservable = function (initialValue, condition) { | |
var obi = ko.observable(initialValue); | |
var computer = ko.computed({ | |
read: function () { return obi(); }, | |
write: function (newValue) { | |
//unwrap value - just to be sure | |
var v = ko.unwrap(newValue); | |
//check condition | |
if (condition(v)) { | |
//set it to the observable | |
obi(v); | |
} | |
else { | |
//reset the value | |
computer.notifySubscribers(); | |
} | |
} | |
}); | |
return computer; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The gist is part of Conditioning Knockout Observables: reject values blog.