我有一个foo
s:的列表
[
{ name: 'Foo 1' type: 'important' },
{ name: 'Foo 2' type: 'normal' },
{ name: 'Foo 3' type: 'purple' }
]
我想呈现这个列表,但其中一些列表有特殊的处理——不仅仅是一个类,而是完全不同的标记。
我的第一直觉是使用组件助手:
{{#each foos as |foo|}}
{{component (join 'foo-' foo.type) foo=foo}}
{{/each}}
这样做的缺点是,I必须为每个type
定义一个组件,服务器可能会向我发送我不知道的新类型。因此,如果没有定义foo-${type}
组件,我想回到基本的foo-generic
组件。
为了做到这一点,我想我应该创建一个助手:
{{#each foos as |foo|}}
{{foo-entry foo}}
{{/each}}
// app/helpers/foo-entry.js
Ember.Helper.helper(function([ foo ]) {
// ...
});
但我还有两个问题:
- 如何在该助手中获取
container
,以便检查component:foo-${foo.type}
是否存在 - 如何从另一个助手中调用
component
助手
我想我可以用一个组件而不是一个助手来完成:
// app/pods/foo-entry/component.js
export default Ember.Component.extend({
tagName: null,
foo: null,
componentName: Ember.computed('foo.type', function() {
const type = this.get('foo.type');
const exists =
this.container.lookupFactory(`component:foo-${type}`) != null ||
this.container.lookupFactory(`template:foo-${type}`) != null;
return exists ? `foo-${type}` : 'foo-generic';
})
})
{{!-- app/pods/foo-entry/template.hbs --}}
{{component componentName foo=foo}}