更新
现在ember 1.10 已经登陆,引入了一种称为块参数的新语法。所以不需要重写_yield 方法。例如,在您的组件模板中,您可以这样做:
<ul>
{{#each item in source}}
<li>
{{! the component is being used in the block form, so we yield}}
{{#if template.blockParams}}
{{yield item}}
{{! no block so just display the item}}
{{else}}
{{item}}
{{/if}}
</li>
{{/each}}
</ul>
然后在使用组件时,您会使用as |var| 将参数传递给{{yield}}
{{! no block, the component will just display the item}}
{{auto-suggest source=model as |item|}}
{{! in the block form our custom html will be used for each item}}
{{#auto-suggest source=model as |item|}}
<h1>{{item}}</h1>
{{/auto-suggest}}
Simple live example
当然,您可以使用 {{yield name age occupation hobbies}} 生成任何变量,并在组件中捕获它们:
{{#x-foo user=model as |name age occupation hobbies|}}
Hi my name is {{name}}, I am {{age}} years old. Major of the times I am {{occupation}}, but also love to {{hobbies}}.
{{/x-foo}}
旧版本
您可以覆盖Ember.Component 的默认_yield 方法,并将context: get(parentView, 'context') 更改为context: get(view, 'context')。
App.AutoSuggestComponent = Ember.Component.extend({
_yield: function(context, options) {
var get = Ember.get,
view = options.data.view,
parentView = this._parentView,
template = get(this, 'template');
if (template) {
Ember.assert("A Component must have a parent view in order to yield.", parentView);
view.appendChild(Ember.View, {
isVirtual: true,
tagName: '',
_contextView: parentView,
template: template,
context: get(view, 'context'), // the default is get(parentView, 'context'),
controller: get(parentView, 'controller'),
templateData: { keywords: parentView.cloneKeywords() }
});
}
}
});