Knockout禁用选择选项标题

时间:2013-07-17 11:39:06

标签: javascript knockout.js html-select

使用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.任何帮助都将不胜感激!

1 个答案:

答案 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);

            }
        });
    }
};