访问knockout.js中$ parent的索引

时间:2022-12-03 07:44:44

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?

在knockout.js 2.1.0中,在使用foreach绑定的模板中,您可以通过$ index()函数访问当前项的索引。在嵌套的foreach绑定中,有没有办法从模板中访问$ parent的索引?

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
    },
    ...
    ]};

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:

有了这个,我想使用索引打印每个模型的路径:[topModel-index subModel-index],这样输出将是这样的:

[0 0]
[0 1]
[1 0]
[2 0]
[2 1]
...

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.

我使用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-->

Should print out: 0 1, 0 2, 1 0, 1 1, 1 2, 2 0, 2 1, ...

应该打印出来:0 1,0 2,1 0,1 1 1,2 2 2 2,......

2 个解决方案

#1


168  

to access the index of the parent object use

访问父对象的索引使用

$parentContext.$index()

rather than

而不是

$parent.index()

#2


2  

The easiest way you can find out is download "knockout context" for chrome. This shows you what data is bound to what element and also lets you see the available functions/variables to that particular bound element. It's an amazing tool for situations like these.

您可以找到最简单的方法是下载chrome的“knockout context”。这将向您显示哪些数据绑定到哪个元素,还可以查看该特定绑定元素的可用函数/变量。对于像这样的情况,这是一个了不起的工具。

#1


168  

to access the index of the parent object use

访问父对象的索引使用

$parentContext.$index()

rather than

而不是

$parent.index()

#2


2  

The easiest way you can find out is download "knockout context" for chrome. This shows you what data is bound to what element and also lets you see the available functions/variables to that particular bound element. It's an amazing tool for situations like these.

您可以找到最简单的方法是下载chrome的“knockout context”。这将向您显示哪些数据绑定到哪个元素,还可以查看该特定绑定元素的可用函数/变量。对于像这样的情况,这是一个了不起的工具。