Skip to content

Instantly share code, notes, and snippets.

@thangtq1009
Forked from bonza-labs/knockout.autonumeric.js
Last active September 8, 2015 04:10
Show Gist options
  • Save thangtq1009/48a7d137bf4092d8fedb to your computer and use it in GitHub Desktop.
Save thangtq1009/48a7d137bf4092d8fedb to your computer and use it in GitHub Desktop.
Knockout.js and autoNumeric.js bindings
ko.bindingHandlers.autoNumeric = function ($) {
function getElementValue(el) {
return parseFloat(el.autoNumericGet(), 10);
}
function getModelValue(accessor) {
return parseFloat(ko.utils.unwrapObservable(accessor()), 10);
}
return {
init: function (el, valueAccessor, bindingsAccessor, viewModel) {
var $el = $(el),
bindings = bindingsAccessor(),
settings = bindings.settings,
value = valueAccessor();
function updateModelValue() {
value(getElementValue($el));
};
if (settings.pSign === 's') {
settings.aSign = ' ' + settings.aSign;
} else {
settings.aSign = settings.aSign + ' ';
}
$el.autoNumeric(settings);
$el.autoNumericSet(getModelValue(value), settings);
$el.change(updateModelValue);
},
update: function (el, valueAccessor, bindingsAccessor, viewModel) {
var $el = $(el),
newValue = getModelValue(valueAccessor()),
elementValue = getElementValue($el),
valueHasChanged = (newValue != elementValue);
if ((newValue === 0) && (elementValue !== 0) && (elementValue !== "0")) {
valueHasChanged = true;
}
if (valueHasChanged) {
$el.autoNumericSet(newValue);
setTimeout(function () { $el.change() }, 0);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment