基于模型类型的Ember组件

3
我知道这有些重复,但我尝试创建一个动态组件渲染器的所有努力都失败了,可能是由于我在Ember概念方面缺乏知识。
我的场景是一个多用途搜索栏,它将在缓存中搜索模型。我希望每个搜索结果根据模型的类型键在搜索输入框下方呈现。Handlebars文件将根据模型类型以components/app-search-<model-type-key>.hbs的语法命名,例如客户机模型的模板名称应为components/app-search-customer.hbs 我的搜索模板如下:
<div class="well well-md">
    <div class="input-group">
        {{input value=searchTerm class="form-control"}}
    </div>
    {{#if searchTerm}} <!-- Updating searchTerm causes results to populate with models -->
    {{#if results.length}}
    <ul class="list-group search-results">
        {{#each result in results}}
            <!-- todo -->
            {{renderSearchComponent model=result}}
        {{/each}}
    </ul>
    {{else}}
        Nothing here Captain
    {{/if}}
    {{/if}}
</div>

我的一个尝试是创建一个名为renderSearchComponent的辅助函数,代码如下:

Ember.Handlebars.registerHelper('renderSearchComponent', function(model, options) {
    var modelType = options.model.constructor.typeKey,
        componentPath,
        component,
        helper;
    if (typeof modelType === 'undefined') {
        componentPath = "app-search-default";
    } else {
        componentPath = "app-search-" + modelType;
    }
    component = Ember.Handlebars.get(this, componentPath, options),
    helper = Ember.Handlebars.resolveHelper(options.data.view.container, component);
    helper.call(this, options);
});

当运行此代码时,options.model 抛出 TypeError: options.model is undefined 错误,并且我还遇到了以下错误:
Error: Assertion Failed: Emptying a view in the inBuffer state is not allowed and should not happen under normal circumstances. Most likely there is a bug in your application. This may be due to excessive property change notifications.

我已经试了好几个小时了,想要做出正确的结果。我所要求的是否可能实现?

谢谢您提前帮忙。

2个回答

2
我知道这是一年前的问题,但是 Ember 自版本 1.11+ 有了新的 组件助手 可以动态渲染组件。
{{#each model as |post|}}
  {{!-- either foo-component or bar-component --}}
  {{component post.componentName post=post}}
{{/each}}

0

你走在了正确的道路上,一个可行的例子可以是:

import {handlebarsGet} from "ember-handlebars/ext";

Ember.Handlebars.registerHelper('renderSearchComponent', function(value, options) {

  var propertyValue;
  if (options) {

    if ( options.types[0] !== 'STRING' ) {
      var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this;
      propertyValue = handlebarsGet(context, value, options);
      propertyValue = propertyValue.constructor.typeKey;
    } else {
      propertyValue = value;
    }

  } else {
    options = value;
    propertyValue = 'default';
  }

  var property = 'app-search-'+propertyValue;
  var helper = Ember.Handlebars.resolveHelper(options.data.view.container, property);
  if (helper) {
    return helper.call(this, options);
  }

});

这个帮助程序允许传递字符串、空值或绑定属性。

{{renderSearchComponent}}
{{renderSearchComponent 'book'}}
{{renderSearchComponent result}}

助手的内部细节没有完全记录,我认为这是因为它们不是公共API。但是您可以通过查看助手源代码来获取灵感。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接