UPDATE
现在余烬1.10 http://emberjs.com/blog/2015/02/07/ember-1-10-0-released.html已经落地,引入了一种称为块参数的新语法。所以不需要覆盖_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>
然后当使用该组件时,您会得到传递给的参数{{yield}}
using as |var|
{{! 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}}
简单的实例 http://emberjs.jsbin.com/sevihivuri/1/edit?html,js,output
当然,您可以使用生成任何变量{{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}}
对于旧版本
您可以覆盖默认值_yield
的方法Ember.Component
,并更改context: get(parentView, 'context')
to 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() }
});
}
}
});