Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
};
@KeesCBakker

This comment has been minimized.

Copy link
Owner Author

@KeesCBakker KeesCBakker commented Sep 7, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment