Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 421
NickL Avatar asked Jul 17 '13 11:07

NickL


1 Answers

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

            }
        });
    }
};
like image 121
Ilya Avatar answered Nov 18 '22 01:11

Ilya