如果您还需要可变视图类,您可以使用以下工具:
列表视图.hbs
{{each item in list itemViewClass=view.Item}}
列表视图.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的实用方法mutableView
import 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} '`);
})
});
};