Knockout JS Conditioned Observable
"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
This comment has been minimized.
The gist is part of Conditioning Knockout Observables: reject values blog.