【问题标题】:Accessing Index in #each in emberjs在 emberjs 中访问 #each 中的索引
【发布时间】:2013-11-16 17:09:34
【问题描述】:

请查看随附的代码

http://jsbin.com/atuBaXE/2/

我正在尝试使用 {{@index}} 访问索引,但似乎没有编译。我认为车把支持这一点

{{#each item in model}}
  {{@index}} 
  {{item}}
{{/each}}

这行不通,我不知道是否支持 {{@index}}

我正在使用

  • Ember.VERSION : 1.0.0
  • Handlebars.VERSION : 1.0.0

【问题讨论】:

标签: javascript ember.js handlebars.js


【解决方案1】:

更新

this PR 开始,现在可以使用带索引的 each 助手,采用新的块参数语法。这在 canary 上可用,希望在 ember 1.11 中默认启用

{{#each model as |item index|}}
  <li>
    Index: {{index}} Content: {{item}}
  </li>
{{/each}}

Live sample

旧版本

您可以使用{{_view.contentIndex}}

{{#each item in model}}
  <li>
    Index: {{_view.contentIndex}} Content: {{item}}
  </li>
{{/each}}

Live sample

【讨论】:

  • 有没有办法获得 1 索引值?例如。对于 n 个项目的数组,第一项应返回 1(不是 0),最后一项应返回 n(不是 n-1)
  • 我认为唯一的方法是将模型包装在带有索引的计算属性中,就像这样emberjs.jsbin.com/xeboqegu/1/edit
  • 如果每个块中的项目被更新,例如通过更改它们的排序顺序 _view.contentIndex 不会为所有项目更新,并且可能导致不正确的索引值。
  • 会徽支持块语法吗? = each model as |item index| 不适合我。
  • @loostro 我创建了一个助手,它只是增加传入的数字以获取基于 1 的索引:pastebin.com/jphC3Xnh
【解决方案2】:

不,它在 Ember 的 Handlebars 版本中不存在,一种方法是使用项目控制器并向其添加一个属性,说明它是第一个还是最后一个等。

App.IndexController = Ember.ArrayController.extend({
  itemController: 'itemer'
});

App.ItemerController = Ember.ObjectController.extend({
  needs:['index'],
  isFirst: function(){
    return this.get('color') === this.get('controllers.index.firstObject.color');
  }.property('controllers.index.firstObject')
});

http://emberjs.jsbin.com/aPewofu/1/edit

【讨论】:

  • 我觉得你写的真的很棒,我相信任何人都会利用它。
  • 两个控制器耦合太紧会有危险吗?
  • 不危险,但缺乏可重用性。这一切都取决于用例。
【解决方案3】:

我喜欢@kingpin2k 的回答——Ember 方式是使用控制器来装饰模型,在这种情况下,我们希望通过添加索引属性来装饰它,以表示它在集合中的位置。

我的做法略有不同,为手头的任务构建了一个单独的实例控制器集合:

App.PostsIndexController = Ember.ArrayController.extend({
  indexedContent: function() {
    get('content').map(function(item, index) {
      App.PostsItemController.create({
        content: item,
        index: index
      });
    });
  }.property('content')
});

App.PostsItemController = Ember.ObjectController.extend({
  index: null
});

【讨论】:

    【解决方案4】:

    注意,关于 @index 语法,截至 2014 年 10 月:

    Ember 不支持 @index(或任何其他 @data 类型 属性)。

    https://github.com/toranb/ember-template-compiler/issues/16#issuecomment-38823756

    【讨论】:

      【解决方案5】:

      如果您只是想在视图中将索引显示为 1 索引值,您也可以试一试CSS Counters。他们是supported 一直到IE 8。

      【讨论】:

        猜你喜欢
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多