我知道这有点重复,但是我所有创建动态组件渲染器的努力都失败了,可能是因为我缺乏余烬概念方面的知识。
My Scenario是一个多用途搜索栏,它将在缓存中搜索模型。我希望每个搜索结果都根据模型的类型键呈现在搜索输入下方。车把文件将根据模型类型命名,语法为组件/app-search-
我的搜索模板如下所示:
<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);
});
当它运行时,选项. model抛出:TypeError:选项.model未定义
,此外我还有以下错误:
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.
我已经眨了几个小时的眼睛,试图把这件事做好。我所要求的可能吗?
提前谢谢你。
我知道这是一个一年前的问题,但是Ember从1.11版本开始就有了新的组件助手来动态渲染组件。
{{#each model as |post|}}
{{!-- either foo-component or bar-component --}}
{{component post.componentName post=post}}
{{/each}}
你在正确的道路上,一个工作的例子可能是这样的:
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内部没有完整的文档,我想是因为它们不是公共API。但是你可以通过查看helper源代码来获得灵感。