2012-06-06 15 views
10

Parece que no puedo obtener un foreach anidado para trabajar.Foreach anidado en knockout.js

código JS es:

$(document).ready(function() { 

    function chartValueViewModel(date, price) { 
     this.date = date; 
     this.price = price; 
    } 

    function chartViewModel(id, name, lineType, values) { 
     this.id = id; 
     this.name = name; 
     this.lineType = lineType; 
     this.values = ko.observableArray(values); 
    } 

    function liveCurveViewModel() { 

     this.chartsData = ko.observableArray([]); 
     var chartsData = this.chartsData; 

     this.init = function() { 

      var mappedCharts = $.map(chartValues, 
      function(chart) { 
       var mappedValues = $.map(chart.chartValues, function(value) { 
        return new chartValueViewModel(value.dateTime, value.price); 
       }) 
       return new chartViewModel(chart.id, chart.name, chart.liveCurveTypeId, mappedValues); 
      }); 

      chartsData(mappedCharts); 
     }; 
    } 

    var vm = new liveCurveViewModel(); 
    vm.init(); 
    ko.applyBindings(vm); 

}); 

HTML es:

<ul data-bind="foreach: chartsData "> 
    <li data-bind="text: name"> 
     <ul data-bind="foreach: values"> 
      <li data-bind="text: price"> 
      </li> 
     </ul> 
    </li> 
</ul> 

El bucle exterior se representa correctamente, pero no reciben nada del bucle interior, ni siquiera un mensaje de error. Lo he verificado y el campo de valores en el chartViewModel está lleno.

Respuesta

29

La encuadernación text que tiene en su exterior li sobrescribe el contenido dentro de ella, por lo que está volando su interior foreach. El enlace text establece el texto interno/contenido de texto del elemento, que sobrescribe los elementos secundarios actuales.

Usted quiere hacer algo como:

<ul data-bind="foreach: chartsData "> 
    <li> 
     <span data-bind="text: name"></span> 
     <ul data-bind="foreach: values"> 
      <li data-bind="text: price"> 
      </li> 
     </ul> 
    </li> 
</ul> 
+0

Niemeyer @RP u debe explicar por qué el texto li exterior vinculante sobrescribir la interior. si es posible, explique este comportamiento en detalle. gracias – Thomas

+0

@Thomas - agregó una oración adicional para aclarar que el enlace 'text' establece innertText/textContent. ¡Espero que ayude! –

Cuestiones relacionadas