KnockoutJS学习笔记10:KonckoutJS foreach绑定

 

KnockoutJS foreach绑定用来处理数组,通常用来将一个数组绑定到一个列表或者table中。在foreach绑定中,我们可以使用if、with等嵌套绑定。

示例代码:

<table>
<thead>
<tr><th>First name</th><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
</tr>
</tbody>
</table> <script type="text/javascript">
ko.applyBindings({
people: [
{ firstName: 'Bert', lastName: 'Bertington' },
{ firstName: 'Charles', lastName: 'Charlesforth' },
{ firstName: 'Denise', lastName: 'Dentiste' }
]
});
</script>

绑定规则:

在ViewModel中,people是一个数组,foreach绑定将会遍历这个数组,将每一项生成一个tr,然后添加在tbody中。

binding context

在foreach中,我们可以使用绑定上下文,完整的绑定上下文包括:

  • $data:当前项的数据
  • $index:当前项的序号
  • $parent:当前项的父级数据

要了解更多,请参考完整的数据上下文。

$data示例:

<ul data-bind="foreach: months">
<li>
The current item is: <b data-bind="text: $data"></b>
</li>
</ul> <script type="text/javascript">
ko.applyBindings({
months: ['Jan', 'Feb', 'Mar', 'etc']
});
</script>

如果$data是一个json对象,可以这样使用:

<td data-bind="text: $data.firstName"></td>

$index和$parent示例:

<h1 data-bind="text: blogPostTitle"></h1>
<ul data-bind="foreach: likes">
<li>
<b data-bind="text: name"></b> likes the blog post
<b data-bind=" text: $parent.blogPostTitle"></b>
</li>
</ul>

使用别名 as

尽管可以方便的使用上下文数据,但有些时候给$data起一个更有意义的别名更容易理解,我们来看看as关键字的用法:

<ul data-bind="foreach: { data: people, as: 'person' }"></ul>

在这段代码中,people的每一个数据项被当作person来访问,其实person就是$data

下面是一个完整的例子:

<ul data-bind="foreach: { data: categories, as: 'category' }">
<li>
<ul data-bind="foreach: { data: items, as: 'item' }">
<li>
<span data-bind="text: category.name"></span>:
<span data-bind="text: item"></span>
</li>
</ul>
</li>
</ul> <script>
var viewModel = {
categories: ko.observableArray([
{ name: 'Fruit', items: ['Apple', 'Orange', 'Banana'] },
{ name: 'Vegetables', items: ['Celery', 'Corn', 'Spinach'] }
])
};
ko.applyBindings(viewModel);
</script>

不使用container

在前面的内容中我们介绍了使用虚拟节点来完成绑定,这种虚拟节点同样能够用在foreach绑定中,示例代码:

<ul>
<li class="header">Header item</li>
<!-- ko foreach: myItems -->
<li>Item <span data-bind="text: $data"></span></li>
<!-- /ko -->
</ul> <script type="text/javascript">
ko.applyBindings({
myItems: ['A', 'B', 'C']
});
</script>

这种方法非常实用。

上一篇:poj1006 / hdu1370 Biorhythms (中国剩余定理)


下一篇:基于OpenCV的火焰检测(一)——图像预处理