繁体   English   中英

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

[英]Handlebars - Set ID of Object created with {{each}} Helper

假设我在列表中有许多对象,我想在这个对象的<table/>创建<tr/>元素。 我创建了一个像这样的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

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


更新:

由于我无法使用idBinding解决问题, 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() ......

如果您希望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}}

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

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

我希望它有所帮助!

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM