Skip to content

Instantly share code, notes, and snippets.

@bonza-labs
Created November 5, 2011 09:09
Show Gist options
  • Save bonza-labs/1341303 to your computer and use it in GitHub Desktop.
Save bonza-labs/1341303 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);
}
}
};
}
@SabbeRubbish
Copy link

@AlexZeitler, no this does not work with the latest version of autoNumeric. See my fork of this gist to get going.

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