Skip to content

Instantly share code, notes, and snippets.

@gnab
Last active December 28, 2015 23:29
Show Gist options
  • Save gnab/7579584 to your computer and use it in GitHub Desktop.
Save gnab/7579584 to your computer and use it in GitHub Desktop.
KO numeric extension.
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);
}
};
<span data-bind="number: 1.5"></span>
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;
};
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