knockout $data binding to an HTML element

你离开我真会死。 提交于 2019-12-24 18:12:04

问题


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.


回答1:


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/



来源:https://stackoverflow.com/questions/21124322/knockout-data-binding-to-an-html-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!