Javascript 在knockout.js 中$parent 的访问索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10978551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:51:48  来源:igfitidea点击:

Access index of $parent in knockout.js

javascriptknockout.jsjquery-templates

提问by J?rgen

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 引用者的索引。

<!--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 0, 2 1, ...

回答by Brett Smith

to access the index of the parent object use

访问父对象的索引使用

$parentContext.$index()

rather than

而不是

$parent.index()

回答by Julian

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 的“淘汰赛上下文”。这会显示哪些数据绑定到哪个元素,还可以让您查看该特定绑定元素的可用函数/变量。对于此类情况,这是一个了不起的工具。