Last active
December 28, 2015 23:29
-
-
Save gnab/7579584 to your computer and use it in GitHub Desktop.
KO numeric extension.
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
ko.bindingHandlers.number = { | |
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) { | |
var value = ko.unwrap(valueAccessor()); | |
valueAccessor = function () { | |
return value.toString().replace('.', ','); | |
}; | |
ko.bindingHandlers.text.update(element, valueAccessor, allBindings, viewModel, bindingContext); | |
} | |
}; |
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
<span data-bind="number: 1.5"></span> |
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
ko.extenders['numeric'] = function (target) { | |
var result = ko.computed({ | |
read: target, | |
write: function (newValue) { | |
if (typeof newValue === 'string') { | |
newValue = newValue.replace(',', '.'); | |
newValue = parseFloat(newValue); | |
if (!isNaN(newValue)) { | |
target(newValue); | |
} | |
} | |
else if (typeof newValue === 'number') { | |
if (!isNaN(newValue)) { | |
target(newValue); | |
} | |
} | |
} | |
}); | |
return result; | |
}; |
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
var observable = ko.observable(0).extend({numeric: true}); | |
observable('1,5'); | |
observable(); // 1.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment