敲除$数据绑定到HTML元素 [英] knockout $data binding to an HTML element
问题描述
所以,假设我有一个名为人物的viewmodel,它包含一个个人对象文字数组,如
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 }]
而且我想要数据绑定每个个人到< li>
,如
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>
但是否可能通过 data-bind =with:$ data
,将整个人物对象绑定到< li>
所以,例如,当我点击< li>
时,其他< div>
显示其余的信息,在这个例子中将是年龄和性别?
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?
这就像我想要的< li>
保持人物对象数据,所以我可以在别的地方使用它。
It's like I wanted the <li>
to hold the person object data, so I could use it somewhere else.
推荐答案
一般来说,你想要创建一个 selectedPerson
可以在视图模型级别观察,然后可以执行以下操作:
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>
如果您愿意,您一定可以使用名称周围的链接/按钮。当您单击它时, selectedPerson
将用作处理程序,并将当前数据作为其第一个参数传递。因为, selectedPerson
实际上是一个可观察的,它将以数据作为其值填充它。
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>
快速提示: http://jsfiddle.net/rniemeyer/8dRZ4/
这篇关于敲除$数据绑定到HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!