Reputation: 381
I'm using REST adapter with latest ember-data and latest Ember.js (RC5)
I have model Module
with following mapping:
DS.Model.extend({
type: DS.attr('string'),
url: DS.attr('string'),
text: DS.attr('string'),
header: DS.attr('string')
});
against the API which returns JSON:
{
"status": "success",
"modules": [{
"id": "123456",
"type": "video",
"url": "http://some.where.com/video.mp4"
}, {
"id": "123457",
"type": "text",
"text": "Lorem ipsum dolor sit amet ..."
}, {
"id": "123458",
"type": "feedback",
"header": "Indtast noget feedback til os."
}]
}
The issue I'm having is how to represent them in template? I need to create different views for each of them, but there is no such a thing in handlebars like if type === video then
(only boolean if which make me worries I'm tying to solve problem from the wrong way) render different view:
if type === video
{{view moduleVideo}}
if type === text
{{view moduleText}}
if type === feedback
{{view moduleFeedback}}
How to render different views for different types? Or is there a more Ember.js way to design such a thing?
Upvotes: 1
Views: 271
Reputation: 4310
The analogue of the switch-type structure you have above is to define identifying properties on your model.
App.Module = DS.Model.extend({
// ...
isVideo: function() {
return this.get('type') === 'video';
}.property('type'),
isText: function() {
return this.get('type') === 'text';
}.property('text'),
// ...
});
In your template, you now have booleans:
{{#if isVideo}}
{{view moduleVideo}}
{{/if}}
{{#if isText}}
{{view moduleText}}
{{/if}}
This works, but is undesirable for two reasons:
One way around this might be to make a Handlebars helper to replace {{render}}
that uses the type of the model to select a suitable controller/view/template based on naming conventions.
An alternative would be to give your model a computed property that renders its output and then use a triple-handlebars binding to dump it into your template. You could then override the output property differently for different sub-classes. This would work well with Ember Data's polymorphism.
Edit:
Here's a jsfiddle of what I was trying to describe above.
Upvotes: 1