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;
};
when i am trying to implement your example for displaying date from json using knockoutjs i have error regarding that
ReplyDeleteMicrosoft JScript runtime error: Function expected
on this line.
observable('/Date(' + dt.getTime() + ')/');
Any ideas why this line:
ReplyDeleteko.utils.registerEventHandler(element, "change", function () {
might not fire?
Great Really this helped me lot
ReplyDelete