剔除DatePicker绑定的项目不会禁用DatePicker

我有一个用于日期选择器的自定义敲除绑定.

ko.bindingHandlers.valueAsDatePicker = {...}

当绑定的输入字段状态(启用/禁用)绑定到可观察到的KO时,它不会启用/禁用datepicker图标.

的HTML

<input id="txtRequestedTo" type="text" placeholder="dd/mm/yyyy" 
data-bind="valueAsDatePicker: reqDateTo, disable: reqDateFrom().length < 1" />

自定义绑定

ko.bindingHandlers.valueAsDatePicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);
        formatAndSetDateValue(element, valueAccessor, allBindingsAccessor);

        // Init UI datepicker
        var dateFormat = allBindingsAccessor.dateFormat 

        $(element).datepicker({
            dateFormat: dateFormat,
            changeMonth: true, 
            changeYear: true, 
            yearRange: '1900:' + new Date().getFullYear(), 
            maxDate: 0, 
            showOn: "button",
            buttonImage: "Content/images/sprite-base/sprite/icon-calender.png",
            buttonImageOnly: true,
            constrainInput: false, 
            buttonText: ""          
        });
    },
    update: function(element, valueAccessor, allBindingsAccessor) {
        // Use the value binding
        ko.bindingHandlers.value.update(element, valueAccessor, allBindingsAccessor);
        formatAndSetDateValue(element, valueAccessor, allBindingsAccessor);

        valueAccessor().valueHasMutated(); 
    }
};

我希望禁用日期选择器(如果禁用了该元素),反之亦然.

解决方法:

感谢一百万罗伯特,

这是有效的解决方案.

Using KnockOutJS V3.1

init: function (element, valueAccessor, allBindings) {
...

//Disable the datepicker if the item is disabled or enabled.
    if (allBindings.has('disable')) {
        if (allBindings.get('disable')()) {
            $(element).datepicker('disable');
        }
        else {
            $(element).datepicker('enable');
        }
        var subscription = allBindings.get('disable').subscribe(function (newValue) {
            if (newValue) {
                $(element).datepicker('disable');
            } else {
                $(element).datepicker('enable');
            }
        });

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            subscription.dispose();
        });
    }
}

你必须用

if (allBindings.has('disable')) {

除此以外

allBindings.get('disable')

将不确定,因为视图中并非所有日期选择器绑定字段都具有Disabled属性.

上一篇:javascript-获取从今天到周末的日期


下一篇:javascript-jQuery ui datepicker:删除(取消突出显示)今天的黄色突出显示