基于模型类型的ember组件

时间:2014-04-24 04:08:47

标签: javascript ember.js handlebars.js

我知道这有点重复,但是我创建动态组件渲染器的所有努力都失败了,可能是由于我对ember概念缺乏了解。

我的场景是一个多用途搜索栏,它将搜索缓存中的模型。我希望根据模型的类型键在搜索输入下面呈现每个搜索结果。把手文件将根据模型类型命名,语法为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 个答案:

答案 0 :(得分:2)

我知道这是一个有问题的问题,但是Ember since version 1.11+有新的component helper来动态渲染组件。

{{#each model as |post|}}
  {{!-- either foo-component or bar-component --}}
  {{component post.componentName post=post}}
{{/each}}

答案 1 :(得分: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}}

Helper internals没有完整记录,我认为因为它们不是公共API。但是你可以通过查看helper source code来获取灵感。

相关问题