Jør*_*gen 86 javascript jquery-templates knockout.js
在knockout.js 2.1.0中,在使用foreach绑定的模板中,您可以通过$ index()函数访问当前项的索引.在嵌套的foreach绑定中,有没有办法从模板中访问$ parent的索引?
假设我有这样的数据结构:
var application = {
topModel: [
{
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]}, // this has top:0 and sub:0
{subModel: [{'foo2':'foo2'}, { 'bar2':'bar2'}]} // this has top:0 and sub:1
},
{
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]} // this is top:1 sub:0
},
{
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]} // this is top:2 sub:0
{subModel: [{'foo':'foo'}, { 'bar':'bar'}]} // this is top:2 sub:1
},
...
]};
Run Code Online (Sandbox Code Playgroud)
有了这个,我想使用索引打印每个模型的路径:[topModel-index subModel-index],这样输出将是这样的:
[0 0]
[0 1]
[1 0]
[2 0]
[2 1]
...
Run Code Online (Sandbox Code Playgroud)
我使用foreach绑定了模型,但我无法弄清楚如何在subModel的上下文中访问topModel的索引.以下示例显示了我尝试过的方法,但它不起作用,因为我无法弄清楚如何访问$ parent referrer的索引.
<!--ko foreach: topModel -->
<!--ko foreach: subModel -->
[<span data-bind="text: $parent.index()"></span>
<span data-bind="text: $index()"></span>]
<!--/ko-->
<!--/ko-->
Run Code Online (Sandbox Code Playgroud)
应该打印出来:0 1,0 2,1 0,1 1,1 2 2,2 0,2 ......
Bre*_*ith 181
访问父对象的索引使用
$parentContext.$index()
Run Code Online (Sandbox Code Playgroud)
而不是
$parent.index()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25141 次 |
| 最近记录: |