2

鉴于我有这个代码:

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?

4

3 回答 3

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

于 2012-04-19T09:50:12.860 回答
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()]
});​
于 2012-04-19T11:17:23.163 回答
0

如果您还需要可变视图类,您可以使用以下工具:

列表视图.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} '`);
    })
  });
};
于 2015-03-17T13:35:21.153 回答