Forked from bonza-labs/knockout.autonumeric.js
Last active
September 8, 2015 04:10
-
-
Save thangtq1009/48a7d137bf4092d8fedb 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); | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment