Skip to content

Instantly share code, notes, and snippets.

@SabbeRubbish
Forked from bonza-labs/knockout.autonumeric.js
Last active May 14, 2016 20:42
Show Gist options
  • Save SabbeRubbish/6897914 to your computer and use it in GitHub Desktop.
Save SabbeRubbish/6897914 to your computer and use it in GitHub Desktop.
The previous version of this Gist wasn't up to date anymore with the latest version of autoNumeric (1.9.17). Not saying this works perfectly, but first tests show that it does work.
ko.bindingHandlers.autoNumeric = {
init: function (el, valueAccessor, bindingsAccessor, viewModel) {
var $el = $(el),
bindings = bindingsAccessor(),
settings = bindings.settings,
value = valueAccessor();
$el.autoNumeric(settings);
$el.autoNumeric('set', parseFloat(ko.utils.unwrapObservable(value()), 10));
$el.change(function() {
value(parseFloat($el.autoNumeric('get'), 10));
});
},
update: function (el, valueAccessor, bindingsAccessor, viewModel) {
var $el = $(el),
newValue = parseFloat(ko.utils.unwrapObservable(valueAccessor()), 10),
elementValue = parseFloat($el.autoNumeric('get'), 10),
valueHasChanged = (newValue != elementValue);
if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0")) {
valueHasChanged = true;
}
if (valueHasChanged) {
$el.autoNumeric('set', newValue);
setTimeout(function () { $el.change() }, 0);
}
}
};
@fededalla2
Copy link

Very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment