Skip to content

Instantly share code, notes, and snippets.

@anthonyvscode
Last active October 23, 2015 01:02
Show Gist options
  • Save anthonyvscode/6ae21661f4078e7a4a4d to your computer and use it in GitHub Desktop.
Save anthonyvscode/6ae21661f4078e7a4a4d to your computer and use it in GitHub Desktop.
KnockoutJS accounting.js binding handler
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(["jquery", "knockout", "accounting"], factory);
} else {
// Browser globals
factory($, ko, accounting);
}
}(this, function ($, ko, accounting) {
ko.bindingHandlers.currency = {
currencyOptions: ko.observable({ symbol: "$", decimal: ".", thousand: ",", precision: 2, format: "%s%v" }), //Set the default values.
init: function (element, valueAccessor, allBindingsAccessor) {
//only inputs need this, text values don't write back
if ($(element).is("input") === true) {
var underlyingObservable = valueAccessor(),
interceptor = ko.computed({
read: underlyingObservable,
write: function (value) {
if (value === "") {
underlyingObservable(null);
} else {
underlyingObservable(accounting.unformat(value));
}
}
});
ko.bindingHandlers.value.init(element, function () {
return interceptor;
}, allBindingsAccessor);
}
},
update: function (element, valueAccessor, allBindingsAccessor) {
// Available fields in options object, matching 'settings.currency'
var currencyOptions = ko.unwrap(allBindingsAccessor().currencyOptions !== undefined ? allBindingsAccessor().currencyOptions : ko.bindingHandlers.currency.currencyOptions);
var value = ko.unwrap(valueAccessor());
var formatCurrency = function (float, options) {
return accounting.formatMoney(float, options);
};
if ($(element).is("input") === true) {
//leave the boxes empty by default
value = value !== null && value !== undefined && value !== "" ? formatCurrency(parseFloat(value), currencyOptions) : "";
$(element).val(value);
} else {
//text based bindings its nice to see a 0 in place of nothing
value = value || 0;
$(element).text(formatCurrency(parseFloat(value), currencyOptions));
}
}
};
}));
@anthonyvscode
Copy link
Author

Usage:

<td data-bind="currency: amount, currencyOptions : { symbol: "$", format: '%s %v' }"></td>

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