具有动态选项的日期选择器的淘汰赛绑定

Knockout binding for datepicker with dynamic options

我正在为 jQuery 日期选择器使用敲除绑定。

参考jQuery UI datepicker change event not caught by KnockoutJS

除了我无法动态设置日期选择器选项外,相同的代码工作正常。

如何使用上述参考资料动态地(单击按钮)设置日期选择器选项(如 mindate 最大日期等)link?

首先,您需要使 options 对象成为视图模型的一部分。然后,根据更改,使用新的 options.

更新 datePicker

这样,您可以将任何 options(如 dayNamesdateFormat 等)添加到您的 options 对象,绑定处理程序将更新自动组件。

例如(动态改变minDate):

var viewModel = {
    myDate: ko.observable(new Date("12/01/2013")),
    setToCurrentDate: function() {
        this.myDate(new Date());
    },
    options: {
        // make sure you're using an observable to wrap the value
        minDate: ko.observable(new Date()) 
    },
    changeMinDate: function(){
        this.options.minDate(new Date('01/01/2015'));
    }
};

并且在绑定处理程序中(添加对 options 上更改的订阅):

ko.bindingHandlers.datepicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var $el = $(element);
        var opts = allBindingsAccessor().datepickerOptions;

        //initialize datepicker with some optional options
        var options = ko.mapping.toJS(opts) || {};
        $el.datepicker(options);

        //handle the field changing
        ko.utils.registerEventHandler(element, "change", 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");
        });

        // subscribe to all changes in the options object
        ko.computed(function(){
            var options = ko.mapping.toJS(opts) || {};

            for (var i in options)
                $el.datepicker('option', i, options[i]);
        });
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()),
            $el = $(element),
            current = $el.datepicker("getDate");

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

Fiddle