你没有打电话给 Init。
只需像在更新中所做的那样代理 init 函数以在您的 nullableChecked 初始化函数中进行检查。
ko.bindingHandlers.nullableChecked = {
init: function(element, valueAccessor) {
ko.bindingHandlers.checked.init(element, valueAccessor);
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value == null) element.indeterminate = true;
ko.bindingHandlers.checked.update(element, valueAccessor);
}
};
如果没有初始化,它实际上永远不会在复选框上设置“点击”绑定来告诉淘汰赛某些事情已经改变。如果您查看调试代码 ( http://knockoutjs.com/downloads/knockout-2.2.1.debug.js ),您会看到 init 使用 jQuery 在复选框上设置“单击”事件以进行更新值变化时的可观察值。
ko.bindingHandlers['checked'] = {
'init': function (element, valueAccessor, allBindingsAccessor) {
var updateHandler = function() {
var valueToWrite;
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
} else {
return; // "checked" binding only responds to checkboxes and selected radio buttons
}
var modelValue = valueAccessor(), unwrappedValue = ko.utils.unwrapObservable(modelValue);
if ((element.type == "checkbox") && (unwrappedValue instanceof Array)) {
// For checkboxes bound to an array, we add/remove the checkbox value to that array
// This works for both observable and non-observable arrays
var existingEntryIndex = ko.utils.arrayIndexOf(unwrappedValue, element.value);
if (element.checked && (existingEntryIndex < 0))
modelValue.push(element.value);
else if ((!element.checked) && (existingEntryIndex >= 0))
modelValue.splice(existingEntryIndex, 1);
} else {
ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'checked', valueToWrite, true);
}
};
ko.utils.registerEventHandler(element, "click", updateHandler);
// IE 6 won't allow radio buttons to be selected unless they have a name
if ((element.type == "radio") && !element.name)
ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
},
编辑:这是一个小提琴:http: //jsfiddle.net/cclose/NFfVn/