2012-06-25 6 views
26

Ho trovato un esempio here per creare un elenco di selezione con optgroups utilizzando KnockoutJS. Questo funziona bene, ma voglio associare il valore della discesa per il mio proprio oggetto JavaScript, quindi accedere a una particolare proprietà di tale oggetto:KnockoutJS - Valore di binding della selezione con oggetti optgroup e javascript

<select data-bind="foreach: groups, value:selectedOption"> 
    <optgroup data-bind="attr: {label: label}, foreach: children"> 
     <option data-bind="text: label"></option> 
    </optgroup> 
</select> 
function Group(label, children) { 
    this.label = ko.observable(label); 
    this.children = ko.observableArray(children); 
} 

function Option(label, property) { 
    this.label = ko.observable(label); 
    this.someOtherProperty = ko.observable(property); 
} 

var viewModel = { 
    groups: ko.observableArray([ 
     new Group("Group 1", [ 
      new Option("Option 1", "A"), 
      new Option("Option 2", "B"), 
      new Option("Option 3", "C") 
     ]), 
     new Group("Group 2", [ 
      new Option("Option 4", "D"), 
      new Option("Option 5", "E"), 
      new Option("Option 6", "F") 
     ]) 
    ]), 
    selectedOption: ko.observable(), 
    specialProperty: ko.computed(function(){ 
     this.selectedOption().someOtherProperty(); 
    }) 
}; 

ko.applyBindings(viewModel); 

risposta

38

Una buona scelta per questa situazione è quello di creare un collegamento rapido personalizzato che consente le tue opzioni "fatte a mano" si comportano allo stesso modo delle opzioni create dal binding options (allega l'oggetto come meta-dati). Il legame potrebbe semplicemente apparire come:

ko.bindingHandlers.option = { 
    update: function(element, valueAccessor) { 
     var value = ko.utils.unwrapObservable(valueAccessor()); 
     ko.selectExtensions.writeValue(element, value); 
    }   
}; 

Si potrebbe usarlo come:

<select data-bind="foreach: groups, value: selectedOption"> 
    <optgroup data-bind="attr: {label: label}, foreach: children"> 
     <option data-bind="text: label, option: $data"></option> 
    </optgroup> 
</select> 

campione qui: http://jsfiddle.net/rniemeyer/aCS7D/

+0

Grazie mille! – user888734

+0

Grazie per il tuo aiuto! Semplice ed efficiente. – Mounir

+1

Come aggiungerebbe "optionsCaption" a questa soluzione? @RP Niemeyer –

10

Questa versione con didascalia e se si vuole avere voce genitore selezionato:

<select data-bind="value: selectedOption "> 
    <option data-bind="value:'', text:'Select'"></option> 
    <!-- ko foreach: groups --> 
     <optgroup data-bind="attr:{label: label}"> 
      <option data-bind="value: $data, text:label"></option> 
      <!-- ko foreach: children --> 
       <option data-bind="value: $data, text:label"></option> 
      <!-- /ko --> 
     </optgroup> 
    <!-- /ko --> 
</select> 
+0

eccellente è quello che mi serviva. ko tag di commento – codyc4321

Problemi correlati