8

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!

1 Answer 1

5

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

            }
        });
    }
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.