Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

ember.js - Selecting view type based on model

I have a list of items I'm trying to display with Ember. For each of these items, I'd like to be able to dynamically select the view type to use to display it based on a "message_type" field in each model.

I currently have something like this, which totally sucks and is not scalable:

{{#each message in controller}}

  {{#if message.isImage}}
    {{view App.ImageMessageView}}
  {{/if}}

  .... 

  {{#if message.isVideo}}
    {{view App.VideoMessageView}}
  {{/if}}

{{/each}}

How can you dynamically select a view based on a model's field in Ember?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a similar question that showed 2 ways to do this: Collection of objects of multiple models as the iterable content in a template in Ember.js

rendering items based on a property or their type

I know of two ways to do this:

  1. add a boolean property to each object and use a handlebars {{#if}} to check that property and render the correct view
  2. extend Ember.View and use a computed property to switch which template is rendered based on which type of object is being rendered (based on Select view template by model type/object value using Ember.js)

Method 1

JS:

App.Post = Ember.Object.extend({
  isPost: true
});

App.Bookmark = Ember.Object.extend({
  isBookmark: true
});

App.Photo = Ember.Object.extend({
  isPhoto: true
});

template:

<ul>
  {{#each item in controller.stream}}
      {{#if item.isPost}}
        <li>post: {{item.name}} {{item.publishtime}}</li>
      {{/if}}
      {{#if item.isBookmark}}
        <li>bookmark: {{item.name}} {{item.publishtime}}</li>
      {{/if}}
      {{#if item.isPhoto}}
        <li>photo: {{item.name}} {{item.publishtime}}</li>
      {{/if}}
  {{/each}}
   </ul>

Method 2

JS:

App.StreamItemView = Ember.View.extend({
  tagName: "li",
  templateName: function() {
    var content = this.get('content');
    if (content instanceof App.Post) {
      return "StreamItemPost";
    } else if (content instanceof App.Bookmark) {
      return "StreamItemBookmark";
    } else if (content instanceof App.Photo) {
      return "StreamItemPhoto";
    }
  }.property(),

  _templateChanged: function() {
        this.rerender();
    }.observes('templateName')
})

template:

<ul>
{{#each item in controller.streamSorted}}
    {{view App.StreamItemView contentBinding=item}}
{{/each}}
 </ul>

JSBin example - the unsorted list is rendered with method 1, and the sorted list is rendered with method 2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...