Monday, March 19, 2012

Knockout JS DatePicker Binding

If you are binding to JSON data using Knockout.js, chances are that you may have encountered problems using the jquery ui datepicker control. The following knockout custom binding can be used to handle dates properly with knockout.js and the datepicker control.

    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            try {
                var jsonDate = ko.utils.unwrapObservable(valueAccessor());
                var value = parseJsonDateString(jsonDate);
                var strDate = value.getMonth() + 1 + "/"
                                + value.getDate() + "/"
                                + value.getFullYear();
                element.setAttribute('value', strDate);
            }
            catch (exc) {
            }
            //initialize datepicker with some optional options
            $.datepicker.setDefaults({ dateFormat: 'mm/dd/yy' });
            var options = allBindingsAccessor().datepickerOptions || dateTimePickerOptions;
            $(element).datepicker(options);

            //handle the field changing
            ko.utils.registerEventHandler(element, "change", function () {
                var observable = valueAccessor();
                var dt = new Date($(element).val());
                observable('/Date(' + dt.getTime() + ')/');
            });

            //handle disposal (if KO removes by the template binding)
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).datepicker("destroy");
            });
        },
        update: function (element, valueAccessor) {
            var val = valueAccessor();
            var dt = new Date(element.getAttribute('value'));
            val('/Date(' + dt.getTime() + ')/');
        }
    };

var jsonDateRE = /^\/Date\((-?\d+)(\+|-)?(\d+)?\)\/$/;

var parseJsonDateString = function (value) {
    var arr = value && jsonDateRE.exec(value);
    if (arr) {
        return new Date(parseInt(arr[1]));
    }
    return value;
};

3 comments:

  1. when i am trying to implement your example for displaying date from json using knockoutjs i have error regarding that
    Microsoft JScript runtime error: Function expected
    on this line.
    observable('/Date(' + dt.getTime() + ')/');

    ReplyDelete
  2. Any ideas why this line:

    ko.utils.registerEventHandler(element, "change", function () {

    might not fire?

    ReplyDelete