Friday, February 7, 2014

Knockout Date Format Extender

As you know Knockout is great on two-way binding and provides a clean mechanism for showing data on the page. There will be scenarios where you want to format your data to make it user friendly. This is especially true when you are showing dates. You don’t want to show the default javascript format to your users. You can certainly format dates while doing the databinding. But formatting dates inside your binding quickly becomes clumsy and sometimes you lose your two-way binding.

In this blog I will show you how to modularize the date formatting and use it throughout the application. Thanks to the Knockouts extenders which allows us to define our date formatting in an elegant way. If you are not aware of Knockout extenders, please check documentation on their site

Before getting into the extender, I want to tell you about a small javascript library, Momentjs, I use for all my date related functionalities. Momentjs is small javascript library for parsing, validating, manipulating and formatting dates. For more information check their website

Using MomentJS, I can do the date formatting to MM/dd/YYYY format by the following syntax.


MomentJS provides several formatting options. For more information check their website.
Coming back to knockout extender, let’s create an extender called dateformat which format the observable with the specified format.

    ko.extenders.dateformat = function (target, format) {
        var result = ko.computed({
            read: target,
            write: function (newValue) {
        }).extend({ notify: 'always' });

        //initializing with the formatted value

        //return the new computed observable
        return result;

We need to define this extender only once. In Durandal you can define it in the main.js.

This extender can be consume while defining the observable as below:

    var DateOfBirth = ko.observable(new Date('1/4/2000')).extend({ dateformat: 'L' });      

That’s all we need to do. The databinding in the view is same as earlier.

<span data-bind="text: DateOfBirth"></span>

You can use this dateformat extender throughout your website with different format options.

No comments:

Post a Comment