Last active
October 23, 2015 01:02
-
-
Save anthonyvscode/6ae21661f4078e7a4a4d to your computer and use it in GitHub Desktop.
KnockoutJS accounting.js binding handler
This file contains hidden or 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
(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)); | |
} | |
} | |
}; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: