Knockout binding formatters for date and currency
Thursday, February 23, 2012 at 4:15AM
Dependency
- Requires Knockout
- jQuery (for setting text())
- ASP.NET (for the formatting functions).
ko.bindingHandlers.date = {
update: function(element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var d = "";
if (valueUnwrapped) {
var m = /Date\([\d+-]+\)/gi.exec(valueUnwrapped);
if (m) {
d = String.format("{0:dd/MM/yyyy}", eval("new " + m[0]));
}
}
$(element).text(d);
}
};
ko.bindingHandlers.money = {
update: function(element, valueAccessor, allBindingsAccessor) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var m = "";
if (valueUnwrapped) {
m = parseInt(valueUnwrapped);
if (m) {
m = String.format("{0:n0}", m);
}
}
$(element).text(m);
}
};
Usage:
- data-bind="money: myMoney"
- data-bind="date: myDate"
Note:
Dates are converted from ASP.NET's date format: \/Date(1000+1000)\/
SharePoint,
code 





Reader Comments (5)
Awesome. Thanks!
Uncaught TypeError: Object function String() { [native code] } has no method 'format'
@Edward
If you are getting that error you aren't using ASP.NET. Format is one of the many extra javascript methods injected by ASP.NET
how can you make this work on mvc4 with .net 4.0 I get the string.format is not a function as well.
Conrad, Have a look at this article:
http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery
It looks like the reference to MicrosoftAjax libraries were finally removed in MVC, so I recommend adding those functions to the native String object yourself.