Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

javascript - Access index of $parent in knockout.js

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

to access the index of the parent object use

$parentContext.$index()

rather than

$parent.index()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...