Access index of $parent in knockout.js

こ雲淡風輕ζ 提交于 2019-11-27 19:56:25

问题


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

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]
...

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-->

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


回答1:


to access the index of the parent object use

$parentContext.$index()

rather than

$parent.index()



回答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.



来源:https://stackoverflow.com/questions/10978551/access-index-of-parent-in-knockout-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!