Reputation: 810
So, suppose I have this viewmodel named people which consists of an array of person object literals, like
[{ name = John, age = 30, sex = male },
{ name = Mike, age = 29, sex = male },
{ name = Anna, age = 28, sex = female }]
And suppose I wanted to data-bind each person to an <li>
, like
<ul data-bind="foreach: people">
<li data-bind="text: name"></li>
</ul>
But, is it possible, maybe through data-bind="with: $data"
, to bind the whole person object to the <li>
so, for example, when I click the <li>
some other <div>
displays the rest of the information, which in this example would be age and sex?
It's like I wanted the <li>
to hold the person object data, so I could use it somewhere else.
Upvotes: 1
Views: 1300
Reputation: 114792
Generally, you would want to create like a selectedPerson
observable at the view model level and then you could do something like:
<ul data-bind="foreach: people">
<li data-bind="click: $parent.selectedPerson">
<span data-bind="text: name"></span>
<div data-bind="visible: $parent.selectedPerson() === $data">
<span data-bind="text: age"></span>
</div>
</li>
</ul>
You could certainly use a link/button around the name, if you like. When you click on it, selectedPerson
will be used as the handler and passed the current data as its first argument. Since, selectedPerson
is actually an observable, it will populate it with the data as its value.
Otherwise, you could certainly have another area to display the details where you do:
<div data-bind="with: selectedPerson">
....
</div>
Quick fiddle: http://jsfiddle.net/rniemeyer/8dRZ4/
Upvotes: 4