简体   繁体   中英

Jquery ui datetimepicker is not working with knockout

I am referencing jQuery UI datepicker change event not caught by KnockoutJS to make datetimepicker work with knockout. So I basically replaced datepicker with datetimepicker to make following code

ko.bindingHandlers.datetimepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {   
        //initialize datetimepicker with some optional options
        var options = allBindingsAccessor().datetimepickerOptions || {};
        $(element).datetimepicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", function () {
            var observable = valueAccessor();
            observable($(element).datetimepicker("getDate"));
        });

        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).datetimepicker("destroy");
        });

    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());

        //handle date data coming via json from Microsoft
        if (String(value).indexOf('/Date(') == 0) {
            value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
        }

        current = $(element).datetimepicker("getDate");

        if (value - current !== 0) {
            $(element).datetimepicker("setDate", value);
        }
    }
};

and in html:

<input data-bind="datetimepicker: myDate, datetimepickerOptions: { minDate: new Date() }" />

With the code, it looked like working but it failed to update what user changed into the corresponding knockout observable.

I debugged the code and found out that

  1. datetimepicker("getDate") gives only date portion with time 00:00.
  2. observable($(element).datetimepicker("getDate")); throws an exception from time to time because observable(x) does not exist sometimes.

Is there anyone having this issue solved?

Update: #2 was resolved by catching the occasional exception.

You might want to try using a recent version of jQuery UI. I was seeing the same behavior that you were until I updated the fiddle to a more recent jQuery/jQuery UI.

Here is a fiddle with the latest bits: http://jsfiddle.net/rniemeyer/MWHNg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM