Created
September 22, 2020 15:24
-
-
Save smailliwcs/c462abea89966b712d6a0a9d60657bcb to your computer and use it in GitHub Desktop.
Knockout extender: numeric
This file contains 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
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()); |
This file contains 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
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