« Dummy guide to install Win 8 on VHD for Boot to VHD | Main | InfoPath - creating sequential filenames without an extra column »
Thursday
Feb232012

Knockout binding formatters for date and currency

 

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)\/

Reader Comments (5)

Awesome. Thanks!

February 23, 2012 | Unregistered CommenterGene

Uncaught TypeError: Object function String() { [native code] } has no method 'format'

September 29, 2012 | Unregistered CommenterEdward

@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

October 2, 2012 | Registered CommenterJohnLiu.NET

how can you make this work on mvc4 with .net 4.0 I get the string.format is not a function as well.

November 15, 2012 | Unregistered Commenterconrad

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.

December 4, 2012 | Registered CommenterJohnLiu.NET

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>