foreach binding for dynamically generated DOM elements

83 views
Skip to first unread message

Tomasz Płonka

unread,
Jun 24, 2015, 5:11:10 AM6/24/15
to knock...@googlegroups.com
Trying to use Knockout, found a problem: I have a JSON data received from a server containing an array of objects with one field being a list of strings. Of course I can generate a list out of it easily:

<ul class='post' data-bind="foreach: $data">
           
<li>
               
<div>
                   
<span data-bind="text: $data.name"></span> (<span data-bind="text: $data.place_type"></span>): <span data-bind='text: $data.trends.length'>&nbsp;</span> trends
               
</div>
               
<ul data-bind="foreach: $data.trends">
                   
<li>
                       
<span data-bind="text: $data"></span>
                   
</li>
               
</ul>
           
</li>
       
</ul>

But now I need to generate every item from the array into a separate <div/> with an unique id, to be used elsewhere. So I can generate the required number of <div/> programatically (knowing the number of items in an (JSON )array, but how to specify bindings in that case?


Tomasz Płonka

unread,
Jun 25, 2015, 4:21:58 AM6/25/15
to knock...@googlegroups.com
OK, found a solution, pretty simple; instead of generating <div/>s first and try to insert bindings into them later, I can generate them using Knockout, like below:

<div id="map" class="map">
   
<!-- ko foreach: $data -->
   
<div class="marker" data-bind="attr: {'id': $index}">

       
<div>
           
<span data-bind="text: $data.name"></span> (<span data-bind="text: $data.place_type"></span>): <span data-bind='text: $data.trends.length'>&nbsp;</span> trends
       
</div>
       
<ul data-bind="foreach: $data.trends">
           
<li>
               
<span data-bind="text: $data"></span>
           
</li>
       
</ul>

   
</div>
   
<!-- /ko -->
</div>

And everything works fine. The only problem is that ids of my layers are simpl numbers, would like to have them named rather like "identifier" + number. Not sure if this is possible though.

Gunnar Liljas

unread,
Jun 26, 2015, 1:46:57 AM6/26/15
to knock...@googlegroups.com
 data-bind="attr: {'id': 'identifier'+ $index()}">

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tomasz Płonka

unread,
Jun 28, 2015, 2:59:07 AM6/28/15
to knock...@googlegroups.com
Thanks a lot; have tried that before, but used $index, not $index().

T.
Reply all
Reply to author
Forward
0 new messages