Knockout disable select option caption
With knockout 2.3.0 the optionsAfterRender
binding has been introduced so that the options can be changed quite flexibly.
I'd like to disable the options caption. At the moment I'm doing
<select data-bind="options: items, optionsCaption:'please select', optionsAfterRender: function(option, item) { ko.applyBindingsToNode(option, {disable: !item}, item); }"></select>
which works, but I have to copy and paste the optionsAfterRender
function everywhere. I've been trying to create a custom bindingHandler to do it in one place, but I'm having difficulty. This is my bindingHandler so far:
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. Any help would be appreciated!
You should apply all bindings together, not step by step, like this:
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);
}
});
}
};
链接地址: http://www.djcxy.com/p/14644.html
上一篇: 延迟点击事件
下一篇: 禁用停用选择选项标题