使用knockout 2.3.0引入了optionsAfterRender
绑定,以便可以非常灵活地更改选项。
我想禁用选项标题。目前我正在做
<select data-bind="options: items, optionsCaption:'please select', optionsAfterRender: function(option, item) { ko.applyBindingsToNode(option, {disable: !item}, item); }"></select>
有效,但我必须在任何地方复制并粘贴optionsAfterRender
函数。我一直在尝试创建一个自定义bindingHandler来在一个地方完成它,但我遇到了困难。
到目前为止,这是我的bindingHandler:
ko.bindingHandlers.disableOptionsCaption = {
init: function (element) {
ko.applyBindingsToNode(element, {
optionsAfterRender: function (option, item) {
ko.applyBindingsToNode(option, {
disable: !item
}, item);
}
});
}
};
I've also created a fiddle here that shows the working version and non-working.任何帮助都将不胜感激!
答案 0 :(得分:5)
您应该将所有绑定应用于一起,而不是一步一步地应用,如下所示:
Html
<select data-bind="disableOptionsCaption:{}"></select>
JS
ko.bindingHandlers.disableOptionsCaption = {
init: function (element,valueAccessor, allBindingsAccessor, viewModel) {
ko.applyBindingsToNode(element, {
options: viewModel.items,
optionsCaption: 'please select',
optionsAfterRender: function (option, item) {
ko.applyBindingsToNode(option, {
disable: !item
}, item);
}
});
}
};