Handlebars - 使用{{each}} Helper创建的对象ID

时间:2013-05-07 06:49:37

标签: ember.js handlebars.js

假设列表中有多个对象,我想从这些对象中<tr/>创建<table/>个元素。我创建了Ember.View,就像这样:

App.TableRowItem = Ember.View.extend({
  classNames: ['list-row'],
  templateName: 'admin/things/tableRow',
  showActionRow: function() {},
  edit: function() {},
  save: function() {},
  delete: function() {}
});

现在,我想在检索到的列表中为Handlebars模板中的每个对象生成一个行项,如下所示:

<table id="someTable">
  <thead>
    <tr><th>Head1</th><th>Head2</th><th>Head3</th></tr>
  </thead>
  <tbody>
    {{# each thing in controller.things}}
      {{log thing}}
      {{view App.TableRowItem contentBinding="thing" id="thing.id"}}
    {{/each}}
  </tbody>
</table>

我希望它能为每个id为id的元素创建一个this.id标记,但我得到以下错误信息:

Uncaught Error: assertion failed: Attempted to register a view with an id already in use: this.id

我做错了什么?如果我没有在id帮助器中设置{{view}},我会收到与上面相同的消息,但它却对id already in use: null ...

抱怨

更新:

由于我无法使用idBinding解决问题,因此我在App.TableRowItem视图中尝试了以下解决方案:

App.TableRowItem = Ember.View.extend({
  tagName: 'tr',
  templateName: 'admin/things/tableRow',

  // this is new!
  init: function() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ ) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    this.set('elementId', text);
  }
});

现在我没有看到任何错误,但我发现模板中不仅有<tr/>admin/things/tableRow),而且还有<div/>元素似乎是我App.TableRowItem没有任何内容的代表!?

虽然调试this.$()给我一个空的<tr id="1fFxV" class="ember-view"></tr>tableRow模板可以通过this.$().closest('tr').next() ...

3 个答案:

答案 0 :(得分:2)

如果您希望this引用循环中的项目,则需要更改{{#each}}格式:

{{#each controller.things}}
  <!-- here the value of `this` is each item in the loop -->
{{/each}}

构建{{each}}的方式,this不是指项目,而是指控制器。

{{#each thing in controller.things}}
  <!-- to reference every item you need to use `thing` instead of `this` -->
{{/each}}

所以这会奏效:

{{#each thing in controller.things}}
  {{view App.TableRowItem contentBinding="thing" idBinding="thing.id"}}
{{/each}}

或者这个:

{{#each controller.things}}
  {{view App.TableRowItem contentBinding="this" idBinding="id"}}
{{/each}}

答案 1 :(得分:2)

我做过类似的事情。我的控制器看起来像这样:

App.ExampleController = Ember.ObjectController.extend({
  id: function() {
    var id = this.get('id');
    return id;
  }.property('id')
});

在我看来是这样的:

{{#each item in items }}
  <div class="exampleItem" {{bindAttr id="item.id"}}>
    Code comes here..
  </div>
{{/each}}

我希望它有所帮助!

答案 2 :(得分:0)

你检查过HTML吗?我想你会发现你将elementId设置为字符串“this.id”,如果你想绑定你必须使用绑定的值。

但是,如果您尝试使用elementIdBinding =“this.id”,则会引发错误,因为一旦创建了元素,就无法修改ID,因为Ember使用ID进行内部预订。

相当不值得尝试设置自定义ID的内部集合并尝试解决您的问题而无需特定的ID