在knockout.js 中$parent 的访问索引 [英] Access index of $parent in knockout.js
问题描述
在knockout.js 2.1.0 中,在使用foreach 绑定的模板中,您可以通过$index() 函数访问当前项目的索引.在嵌套的 foreach 绑定中,有没有办法从模板中访问 $parent 的索引?
In knockout.js 2.1.0, in a template using the foreach binding, you can access the current item's index though the $index() function. In a nested foreach binding, is there any way to access the index of the $parent from a template?
假设我有一个这样的数据结构:
Say I have a data structure like this:
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
},
...
]};
有了这个,我想使用索引打印每个模型的路径:[topModel-index subModel-index],因此输出将类似于:
With this, I want to print the path to each model, using indices: [topModel-index subModel-index], so that the output will be something like:
[0 0]
[0 1]
[1 0]
[2 0]
[2 1]
...
我已经使用 foreach 绑定了模型,但是我不知道如何在 subModel 的上下文中访问 topModel 的索引.以下示例显示了我尝试过的一种方法,但它不起作用,因为我不知道如何访问 $parent 引用者的索引.
I have bound the models using foreach, but I can't figure out how to access the topModel's index in the context of the subModel. The following example shows an approach I have tried, but it doesn't work, as I can't figure out how to access the index of the $parent referrer.
<!--ko foreach: topModel -->
<!--ko foreach: subModel -->
[<span data-bind="text: $parent.index()"></span>
<span data-bind="text: $index()"></span>]
<!--/ko-->
<!--/ko-->
应该打印出:0 1, 0 2, 1 0, 1 1, 1 2, 2 0, 2 1, ...
Should print out: 0 1, 0 2, 1 0, 1 1, 1 2, 2 0, 2 1, ...
推荐答案
访问父对象的索引使用
$parentContext.$index()
而不是
$parent.index()
这篇关于在knockout.js 中$parent 的访问索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!