Created
November 5, 2011 09:09
-
-
Save bonza-labs/1341303 to your computer and use it in GitHub Desktop.
Knockout.js and autoNumeric.js bindings
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.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); | |
} | |
} | |
}; | |
} |
@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
Thanks for sharing. Should this still work?