簡體   English   中英

如何以編程方式調用Ember的組件幫助器?

[英]How do I invoke Ember's component helper programmatically?

我有一個foo的列表:

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

缺點是我必須為每種type定義一個組件,並且服務器可能會向我發送我不知道的新類型。 因此,如果未定義foo-${type}組件,我想回到基本的foo-generic組件。

為此,我想創建一個助手:

{{#each foos as |foo|}}
  {{foo-entry foo}}
{{/each}}

// app/helpers/foo-entry.js
Ember.Helper.helper(function([ foo ]) {
  // ...
});

但是我還有兩個問題:

  1. 我如何在該幫助器中獲取一個container ,以便可以檢查component:foo-${foo.type}存在?
  2. 如何從另一個助手中調用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}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM