鉴于我有这段代码:
Ember.App.View = Ember.View.extend({
templateName: "templateA"
});
Ember.App.View = Ember.View.extend({
templateName: "templateB"
});
Ember.App.ViewC = Ember.CollectionView.extend({
itemViewClass: "Ember.View",
contentBinding: "SomeController"
});
有没有办法将不同模板的视图添加到CollectionView?
答案 0 :(得分:6)
您可以将templateName
计算属性设为itemViewClass
,请参阅http://jsfiddle.net/pangratz666/vGHcD/:
App.MyView = Ember.View.extend({
templateName: function() {
var templateName = Ember.getPath(this, 'content.label');
// return default template if there is no such template
return (!Ember.TEMPLATES[templateName]) ? 'default' : templateName;
}.property('content.label').cacheable(),
// rerender the view if the template name changes
_templateNameChanged: function() {
this.rerender();
}.observes('templateName')
});
App.CollectionView = Ember.CollectionView.extend({
itemViewClass: 'App.MyView'
});
另请查看相关问题:Select view template by model type/object value using Ember.js
答案 1 :(得分:0)
另一种解决方案是使用ghempton/ember-layout,请参阅http://jsfiddle.net/pangratz666/XhfYy/:
App.ViewA = Ember.View.extend({
templateName: "templateA"
});
App.ViewB = Ember.View.extend({
templateName: "templateB"
});
App.ItemView = Ember.View.extend({
template: Ember.Handlebars.compile('{{dynamicView content}}')
});
App.CollectionView = Ember.CollectionView.extend({
itemViewClass: 'App.ItemView'
});
App.controller = Ember.ArrayProxy.create({
content: [App.ViewA.create(), App.ViewB.create()]
});
答案 2 :(得分:0)
如果您还需要可变视图类,可以使用以下工具:
<强> listview.hbs 强>
{{each item in list itemViewClass=view.Item}}
<强> listview.js 强>
import Ember from 'ember';
import { mutableView } from 'utils/mutable-view';
export default Ember.View.extend({
Item: mutableView('content.type', function (type, container) {
if (type === 'type_a') {
return container.lookupFactory('view:item-a-view');
}
if (type === 'type_b') {
return container.lookupFactory('view:item-b-view');
}
}),
});
最后 mutable-view.js
的实用方法 mutableViewimport Ember from 'ember';
var mutableViewTemplate = Ember.Handlebars.compile('{{view view.DynamicView content=view.content}}');
export var mutableView = function(observes, viewSelector) {
return Ember.View.extend({
template: mutableViewTemplate,
__dynamicViewCache: {},
DynamicView: Ember.computed(observes, function () {
var view;
var cache = this.get('__dynamicViewCache');
var modificator = this.get(observes);
view = cache[modificator];
if (view) {
return view;
}
view = viewSelector(modificator, this.get('container'));
if (view) {
cache[modificator] = view;
return view;
}
throw new Error(`Cannot determine view class for '${modificator}' of '${observes} '`);
})
});
};