Select view template by model type/object value using Ember.js

前端 未结 2 922
醉酒成梦
醉酒成梦 2020-12-05 04:29

I would like to store different objects in the same controller content array and render each one using an appropriate view template, but ideally the same view.

I am

相关标签:
2条回答
  • 2020-12-05 04:58

    Based on the solution of @rlivsey, I've added the functionality to change the template when a property changes, see http://jsfiddle.net/pangratz666/ux7Qa/

    App.ItemView = Ember.View.extend({
        templateName: function() {
            var name = Ember.getPath(this, 'content.name');
            return (name.indexOf('foo') !== -1) ? 'foo-item' : 'bar-item';
        }.property('content.name').cacheable(),
    
        _templateChanged: function() {
            this.rerender();
        }.observes('templateName')
    });
    
    0 讨论(0)
  • 2020-12-05 05:10

    You can make templateName a property and then work out what template to use based on the content.

    For example, this uses instanceof to set a template based on the type of object:

    App.ItemView = Ember.View.extend({
        templateName: function() {
            if (this.get("content") instanceof App.Foo) {
                return "foo-item";
            } else {
                return "bar-item";
            }
        }.property().cacheable()
    });
    

    Here's a fiddle with a working example of the above: http://jsfiddle.net/rlivsey/QWR6V/

    0 讨论(0)
提交回复
热议问题