使用动态选项敲除datepicker的绑定

时间:2015-06-16 05:54:45

标签: knockout.js jquery-ui-datepicker

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

请参阅jQuery UI datepicker change event not caught by KnockoutJS

相同的代码工作正常,但我无法动态设置datepicker选项。

如何使用上面的参考链接动态设置datepicker选项(如同最大限度日期等)?

1 个答案:

答案 0 :(得分:6)

首先,您需要将options对象作为视图模型的一部分。然后,在更改后,使用新的datePicker更新options

这样,您可以将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