访问knockout.js中$ parent的索引 [英] Access index of $parent in knockout.js

查看:578
本文介绍了访问knockout.js中$ parent的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆