Skip to content

Instantly share code, notes, and snippets.

@mattsizzle
Last active March 6, 2020 21:37
Show Gist options
  • Save mattsizzle/a6ae00173e2b681e0e4e to your computer and use it in GitHub Desktop.
Save mattsizzle/a6ae00173e2b681e0e4e to your computer and use it in GitHub Desktop.
KnockoutJS - Custom Observables
ko.numericObservable = function(initialValue) {
var _actual = ko.observable(initialValue);
var result = ko.dependentObservable({
read: function() {
return _actual();
},
write: function(newValue) {
var parsedValue = parseFloat(newValue);
_actual(isNaN(parsedValue) ? newValue : parsedValue);
}
});
return result;
};
ko.observableBoolean = function(initialValue) {
var _actual = ko.observable(initialValue);
var result = ko.dependentObservable({
read: function() {
return _actual();
},
write: function(initialValue) {
switch(initialValue){
case "0": case null: _actual(false); // Add false matches here
default: _actual(Boolean(initialValue));
}
}
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment