Foreach instead of parameter binding ... how can I replicate the functionality of the "optionsCaption"?

I have been working with KnockoutJS this week and have a rather specific problem that I hope someone else comes across and resolves in front of me ...

In fact, I bind the selection box, but I should be able to control the parameter tags themselves (for example, disable), so this means that I could not use the "options" binding, which, of course, does not give you excellent control over the option tags .. Here is what I came up with (it works!)

<select data-bind="foreach: $root.availableLabels, value: Label, enable: !IsConfirmed(), optionsCaption: 'Please select...'">
    <option data-bind="text: Value, value: $data, css: { 'paired-label': IsPaired }, disable: IsPaired"></option>
</select>

My problem is with the "optionsCaption", because I use the foreach method to generate internal parameters that do not work automatically, as if I could use the simpler "Parameters" binding found on the knockout page ... so if there are objects that I I repeat, they have a "Label" value of zero, it simply displays the first one in the list, and not "Please select ...", which would be ideal.

Does anyone know about this? I did not post my view model code, as I'm not sure if this is really relevant, but if necessary, just ask!

In short, the problem is that I need to use foreach so that I can set the css / attr bindings on the parameters, but I still need "unallocated".

Thanks so much for any help!

+4
2

. optionsAfterRender.

, , <select> knockout.js .

:

, optionsAfterRender. , - :

  • , , undefined
<select size=3 data-bind="
    options: myItems,
    optionsText: 'name',
    optionsValue: 'id',
    optionsAfterRender: setOptionDisable">
</select>

<script type="text/javascript">
    var vm = {
        myItems: [
            { name: 'Item 1', id: 1, disable: ko.observable(false)},
            { name: 'Item 3', id: 3, disable: ko.observable(true)},
            { name: 'Item 4', id: 4, disable: ko.observable(false)}
        ],
        setOptionDisable: function(option, item) {
            ko.applyBindingsToNode(option, {disable: item.disable}, item);
        }
    };
    ko.applyBindings(vm);
</script>

, , , -. , .

:

self.setOptionDisable= function(option, item) {
    option.disabled = item.disable()
} 
+3

foreach ", ...":

<select data-bind="value: Label, enable: !IsConfirmed()">
    <option value="">Please select...</option>
    <!-- ko foreach: $root.availableLabels -->
    <option data-bind="text: Value, 
                       value: $data, 
                       css: { 'paired-label': IsPaired },
                       disable: IsPaired"></option>
    <!-- /ko -->
</select>

: JSFiddle

+5

All Articles