jQuery UI datepicker change event not caught by KnockoutJS

后端 未结 13 2403
长发绾君心
长发绾君心 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:33

    Although all of these answers saved me a lot of work, none of them fully worked for me. After selecting a date, the binded value would not update. I could only get it to update when changing the date value using the keyboard then clicking out of the input box. I fixed this by augmenting RP Niemeyer's code with syb's code to get:

    ko.bindingHandlers.datepicker = {
            init: function (element, valueAccessor, allBindingsAccessor) {
                //initialize datepicker with some optional options
                var options = allBindingsAccessor().datepickerOptions || {};
    
                var funcOnSelectdate = function () {
                    var observable = valueAccessor();
                    observable($(element).datepicker("getDate"));
                }
    
                options.onSelect = funcOnSelectdate;
    
                $(element).datepicker(options);
    
                //handle the field changing
                ko.utils.registerEventHandler(element, "change", funcOnSelectdate);
    
                //handle disposal (if KO removes by the template binding)
                ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                    $(element).datepicker("destroy");
                });
    
            },
            update: function (element, valueAccessor) {
    
                var value = ko.utils.unwrapObservable(valueAccessor());
                if (typeof(value) === "string") { // JSON string from server
                    value = value.split("T")[0]; // Removes time
                }
    
                var current = $(element).datepicker("getDate");
    
                if (value - current !== 0) {
                    var parsedDate = $.datepicker.parseDate('yy-mm-dd', value);
                    $(element).datepicker("setDate", parsedDate);
                }
            }
        };
    

    I suspect putting the observable($(element).datepicker("getDate")); statement in its own function and registering that with options.onSelect did the trick?

提交回复
热议问题