Skip to content

Instantly share code, notes, and snippets.

@smailliwcs
Created September 22, 2020 15:24
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 smailliwcs/c462abea89966b712d6a0a9d60657bcb to your computer and use it in GitHub Desktop.
Save smailliwcs/c462abea89966b712d6a0a9d60657bcb to your computer and use it in GitHub Desktop.
Knockout extender: numeric
function log(value) {
console.log(typeof value + ": " + value);
}
ko.extenders.numeric1 = function (target) {
return ko.computed({
read: target,
write: function (value) {
var number = parseFloat(value);
target(isNaN(number) ? value : number);
}
});
};
var x = ko.observable().extend({ numeric1: {} });
x(1);
log(x());
x("2");
log(x());
x("three");
log(x());
ko.extenders.numeric2 = function (target) {
target.value = ko.computed(function () {
return parseFloat(target());
});
return target;
};
var y = ko.observable().extend({ numeric2: {} });
y("4");
log(y());
log(y.value());
y("five");
log(y());
log(y.value());
number: 1
number: 2
string: three
string: 4
number: 4
string: five
number: NaN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment