Ember 每个循环加倍。使用内部每个循环变量的值绑定到 属性 在外部每个循环的变量中命名相同

Ember double each loop. Using value of inner each loop variable to bind to property named the same in the variable of the outer each loop

为了详细说明标题,我要实现的是以下内容。

我正在 Ember 中构建交互式 table 组件。这是剥离的模板:

<table>
    <thead>
        <tr>
            {{#each header in headers}}
                <th>{{header}}</th>
            {{/each}}
        </tr>
    </thead>
    <tbody>
        {{#each row in rows}}
        <tr>
            {{#each header in headers}}
                <td>{{input value=row.[header]}}</td> <!-- can I bind to row.header here somehow? -->
            {{/each}}
        </tr>
        {{/each}}
    </tbody>
</table>

我希望特定行和特定列的每个输入字段绑定到该行的 row object,特别是 属性 的命名方式 [=43] =] 列被命名。

本质上,我想使用 header 变量的值来绑定 object 行中的一个 属性 由该值调用(如果当前 header 有值 'title' 然后我想绑定到 row.title)

这是我如何初始化这些 object 的示例:

var headers = ['title','description'];

var rows = [],
    row = {};

for(var i = 0; i < headers.length; i++) {
    row[headers[i]] = '';  // this line does similar thing to what I am trying to achieve
}

rows.push(row);

/* This gives

    rows = [
        {
            title: '',
            description: ''
        }
    ]
*/

经过研究,我在 Handlebars 文档中发现 this 说我可以像这样访问属性:

{{#each articles.[10].[#comments]}}
    ...
{{/each}}

根据文档,这与以下内容几乎相同:

articles[10]['#comments']

但是,使用:

rows.[header] 

对我不起作用,因为它试图从字面上访问 rows object(即 rows.header)的 'header' 属性 而不是header 变量中包含的值。

您始终可以扩展文本字段组件并至少获得您正在寻找的值。

App.DynamicInputComponent = Ember.TextField.extend({
  row: null,
  col: null,
  value: function(){
    var row = this.get('row');
    var col = this.get('col');

    return row[col];
  }.property('row', 'col')
});

然后,在您的模板中您可以:

<table>
  {{#each item in model}}
  <tr>
    {{#each col in columns}}
      <td> {{ dynamic-input type='text' row=item col=col }} </td>
    {{/each}}
  </tr>
  {{/each}}
</table>

(部分)工作解决方案here

此功能现在可以在 Ember 中轻松实现(since 1.13) using the new and awesome inline helpers mut and get:

实现这一点的方法分为两个基本步骤:

  1. 使用 getr 中动态查找 属性,命名为 heach 迭代中的值。例如,如果 h = 'title',那么这将是 return r['title']
  2. 使用mut指定这个提取的值对于我们的输入组件是可变的(特别是它的值属性)。

这是整个 each 的样子:

{{#each rows as |r|}}
<tr>
  {{#each headers as |h|}}
  <td>
    <input onkeyup={{action (mut (get r h)) value="target.value" }}>
  </td>
  {{/each}}
</tr>
{{/each}}

Detailed example on Ember Twiddle