可能你可以在这里采取一些不同的方法。这是一个想法(请随意使用比 更好的名称optionsPlus
):
ko.bindingHandlers.optionsPlus = {
preprocess: function(value, name, addBindingCallback) {
//add optionsCaption to the bindings against a "caption" sub-observable
addBindingCallback("optionsCaption", value + ".caption");
//just return the original value to allow this binding to remain as-is
return value;
},
init: function(element, valueAccessor) {
var options = valueAccessor();
//create an observable to track the caption
if (options && !ko.isObservable(options.caption)) {
options.caption = ko.observable();
}
//call the real options binding, return to control descendant bindings
return ko.bindingHandlers.options.init.apply(this, arguments);
},
update: function(element, valueAccessor, allBindings) {
var options = valueAccessor(),
value = ko.unwrap(options);
//set the caption observable based on the length of data
options.caption(value.length === 1 ? null : allBindings.get("defaultCaption"));
//call the original options update
ko.bindingHandlers.options.update.apply(this, arguments);
}
};
你会像这样使用它:
<select data-bind="optionsPlus: choices, defaultCaption: 'choose one...'"></select>
它从您的 observableArray/array 中创建一个caption
observable,并在最初和每当更新选项时更新标题(如果使用 observableArray)。
示例:http: //jsfiddle.net/rniemeyer/jZ2FC/