0

我试图在我的 Ember(ember-data) 模型中放置一个属性,该属性只是要包含在通用表组件中的属性数组。起初我只是将它添加到我的模型中:

tableColumns: function() {
  return ['age', 'gender', 'whatever'];
}.property()

但是现在我发现自己跳过了子组件中的圈子,以便轻松地遍历这些属性并为每个模型实例调用它们的值。

由于列会随每个模型而变化,我认为这是一个很好的解决方案。有没有更好的办法?

特别是当对于每一行(模型实例)我只想说一些不合理的东西时,比如下面的假想片段。

{{#each col in tableColumns}}
  <td>{{model.col}}</td>
{{/each}}

我试图保持无控制器并保持我的组件通用。

编辑:

现在在行组件中我正在这样做,然后遍历 hbs 中的“cols”。但这感觉不对,我正在进入异步部分(某些列需要进行外部调用),我认为这会导致一些问题,所以我想找到更好的方法。

this.get('model').tableColumns().forEach(function(cell){
  cols.push(that.get('model._data.' + cell));
});
4

1 回答 1

1

您似乎正在编写数据表组件。我最近这样做了,但遗憾的是我无法与您分享我的代码。我将在一般意义上解释它是如何工作的:

首先,我定义了一个“列”对象数组。每列都有一个“属性”属性,除其他外(如标题值、CSS 样式等)。

我的数据表组件标签如下所示:

{{data-table columns=columns content=content rowAction="open" empty-label="Nothing found."}}

在此示例中,该columns属性是我的列定义数组,并且content是要显示的记录数组。

在组件的实现中,我的模板是这样的:

<tbody>
  {{#each row in content}}
  <tr>
    {{#each column in columns}}
    <td>
      <div>{{tablecell row column}}</div>
    </td>
    {{/each}}
  </tr>
  {{else}}
  <tr>
    <td colspan="7"> <em>{{emptyLabel}}</em>
    </td>
  </tr>
  {{/each}}
</tbody>

最后,我使用了一个自定义的车把组件 ( tablecell):

Ember.Handlebars.helper('tablecell', function(row, column, options) {
  if (!column.property) {
    Ember.warn('You must specify a "property" value for a table column:%@'.fmt(JSON.stringify(column)));
    return '';
  }
  // if it's a function, call passing the row object and return its value.
  if (typeof column.property === 'function') {
    return column.property(row);
  }
  // otherwise, it is a simple property name.  return it from the row object
  return row.get(column.property);
});

您可能会注意到我的tablecell助手可以处理property字符串或函数的属性。这让我可以对显示值进行一些自定义调整。

我没有给你完整的解决方案,但希望这是足够的信息让你上路!

于 2015-05-19T19:49:57.227 回答