jQuery UI datepicker change event not caught by KnockoutJS

后端 未结 13 2416
长发绾君心
长发绾君心 2020-11-22 16:16

I\'m trying to use KnockoutJS with jQuery UI. I have an input element with a datepicker attached. I\'m currently running knockout.debug.1.2.1.js and it seems th

13条回答
  •  日久生厌
    2020-11-22 16:23

    I think that for the jQuery UI datepicker it is preferable to use a custom binding that will read/write with Date objects using the APIs provided by the datepicker.

    The binding might look like (from my answer here):

    ko.bindingHandlers.datepicker = {
        init: function(element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = allBindingsAccessor().datepickerOptions || {},
                $el = $(element);
    
            $el.datepicker(options);
    
            //handle the field changing by registering datepicker's changeDate event
            ko.utils.registerEventHandler(element, "changeDate", function () {
                var observable = valueAccessor();
                observable($el.datepicker("getDate"));
            });
    
            //handle disposal (if KO removes by the template binding)
            ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
                $el.datepicker("destroy");
            });
    
        },
        update: function(element, valueAccessor) {
            var value = ko.utils.unwrapObservable(valueAccessor()),
                $el = $(element);
    
            //handle date data coming via json from Microsoft
            if (String(value).indexOf('/Date(') == 0) {
                value = new Date(parseInt(value.replace(/\/Date\((.*?)\)\//gi, "$1")));
            }
    
            var current = $el.datepicker("getDate");
    
            if (value - current !== 0) {
                $el.datepicker("setDate", value);
            }
        }
    };
    

    You would use it like:

    
    

    Sample in jsFiddle here: http://jsfiddle.net/rniemeyer/NAgNV/

提交回复
热议问题