Bind to a selected item of the foreach binding with knockout.js

2,161 views
Skip to first unread message

Eystein

unread,
Jul 15, 2012, 6:10:03 PM7/15/12
to knock...@googlegroups.com

I am using knockout.js and the ko.mapping plugin to bind a list of json object to an html grid. Lets call each item a card (simplified example below)

{
   
"card": [
       
{
           
"Id": "cards/1",
           
"category": "Demo",
           
"title": "Card 1",
           
"description": "bla bla",
           
"picture": "demo1.jpg ",
           
"madeBy": "user/1"
       
},
       
{
           
"Id": "cards/2",
           
"category": "Demo",
           
"title": "Card 2",
           
"description": "bla bla",
           
"picture": "demo2.jpg",
           
"madeBy": "user/2"
       
}
   
]
}

I bind each elemet like this:

 <div data-bind="foreach: card">
   
<span data-bind="text:title"></span>
   
<a data-bind='click: show'><img data-bind="attr:{src: picture}" /></a>
</div>

When the user clicks on a card, I would like to show the selected card in a different div (outside of theforeach) with some more properties from the selected json object

Who do I bind to one selected card from the view model?

I am trying something like (but not getting any data):

<h1 data-bind="text: $data.title"> </h1>

rpn

unread,
Jul 16, 2012, 8:18:05 PM7/16/12
to knock...@googlegroups.com
Generally, you would have a "selected" observable at the root level and populate it when you click on an item.  Then, you can bind a section to the "selected" observable using something like the "with" binding.  Something like:

var viewModel = {
    items: ko.observableArray([
      { id: 1, name: "one" },
      { id: 2, name: "two" }
   ]),
    selected: ko.observable()
};


<ul data-bind="foreach: items">
    <li>
          <a href="#" data-bind="click: $root.selected, text: name"></a>
    </li>
</ul>

<div data-bind="with: selected">
    <span data-bind="text: id"></span>
    <span data-bind="text: name"></span>
</div>

Note that you can certainly create a "selecItem" method on your view model and use it to populate the "selected" observable.  I took a shortcut in the code about and just bound it directly against $root.selected, as a click handler will pass the current data as the first argument, which will set the value of the observable.

Hope this helps.
Reply all
Reply to author
Forward
0 new messages