我有一个日期选择器的自定义knockoutJs绑定。
ko.bindingHandlers.valueAsDatePicker = {...}
当绑定输入字段状态(启用/禁用)绑定到KO observable时,它不会启用/禁用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();
}
};
如果元素被禁用,我希望禁用日期选择器,以及反之亦然。
答案 0 :(得分:2)
感谢一百万罗伯特,
以下是有效的解决方案。
使用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')
将是未定义的,因为视图中的所有datepicker绑定字段都没有disabled属性。
答案 1 :(得分:1)
这里的技巧是将已禁用的绑定作为可观察对象进行访问,以便您可以附加手动订阅。目前,禁用表达式的结果传递给bindingHandler(通过allBindingAccessor)。
您获得订阅后,您可以调用DatePicker的禁用选项
<强> HTML 强>
<input id="txtRequestedTo" type="text" placeholder="dd/mm/yyyy"
data-bind="valueAsDatePicker: reqDateTo, disable: reqDateFrom.disabled" />
<强> JAVASCRIPT 强>
var reqDateFrom = ko.observable();
var reqDateTo = ko.observable();
reqDateTo.disabled = ko.computed( function() {
return (reqDateFrom() || '').length === 0;
} );
ko.bindingHandlers.valueAsDatePicker {
init: function(element, valueAccessor, allBindingsAccessor) {
....
// ko 3.0 syntax. For 2.x use allBindingAccessor['disable']
var subscription = allBindingAccessor.get('disable').subscribe( function(newValue) {
$(element).datepicker('option', 'disabled', newValue);
});
// Make sure the subscription is disposed when the element is torn down
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
subscription.dispose();
});
},
update: function(element, valueAccessor, allBindingsAccessor) {
}
}