Skip to content

Instantly share code, notes, and snippets.

@KeesCBakker
Created September 7, 2017 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KeesCBakker/0f732550f95c327545d7cca7a919d319 to your computer and use it in GitHub Desktop.
Save KeesCBakker/0f732550f95c327545d7cca7a919d319 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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