Last active
March 6, 2020 21:37
-
-
Save mattsizzle/a6ae00173e2b681e0e4e to your computer and use it in GitHub Desktop.
KnockoutJS - Custom Observables
This file contains hidden or 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
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; | |
}; |
This file contains hidden or 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
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