jQuery UI datepicker change event not caught by KnockoutJS

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

    Here is a version of RP Niemeyer's answer that will work with the knockout validation scripts found here: http://github.com/ericmbarnard/Knockout-Validation

    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            //initialize datepicker with some optional options
            var options = allBindingsAccessor().datepickerOptions || {};
            $(element).datepicker(options);
    
            //handle the field changing
            ko.utils.registerEventHandler(element, "change", function () {
                var observable = valueAccessor();
                observable($(element).val());
                if (observable.isValid()) {
                    observable($(element).datepicker("getDate"));
    
                    $(element).blur();
                }
            });
    
            //handle disposal (if KO removes by the template binding)
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).datepicker("destroy");
            });
    
            ko.bindingHandlers.validationCore.init(element, valueAccessor, allBindingsAccessor);
    
        },
        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).datepicker("getDate");
    
            if (value - current !== 0) {
                $(element).datepicker("setDate", value);
            }
        }
    };
    

    Changes are to the change event handler to pass the entered value and not the date to the validation scripts first, then only setting the date to the observable if it is valid. I also added the validationCore.init that is needed for custom bindings discussed here:

    http://github.com/ericmbarnard/Knockout-Validation/issues/69

    I also added rpenrose's suggestion for a blur on change to eliminate some pesky datepicker scenarios getting in the way of things.

提交回复
热议问题