When using EmberJs, I need to develop a view that can hold different types of players (such as Youtube, Photosynth, Html Content, etc.) and it should change dynamically based on a controller property that specifies the item to play.
I've already created several views for each type of player, like in the example below:
App.basePlayer = Em.View.extend({
templateName : 'base'
});
App.playerEmpty= App.basePlayer.extend({
templateName : 'empty'
});
App.player1= App.basePlayer.extend({
templateName : 'p1'
});
App.player2= App.basePlayer.extend({
templateName : 'p2'
});
Now, I need to create a view that can append one of these player views in its content. If the view is a normal Ember.View that binds a view stored in a property, it works when initialized, but won't re-render if a new view is set.
To address this issue, I came up with a ContainerView that holds the player:
App.IndexView = Em.CollectionView.extend({
childViews: ['header', App.playerEmpty],
header: Em.View.extend({
templateName : 'h'
})
});
I also created two methods that update the player view when the Item property in the controller changes:
onItemChange : function(){
var item = this.get('controller.item'),
playerClass = null;
if(item === null){
playerClass = App.playerEmpty;
}
else if(item instanceof App.Item1){
playerClass = App.player1;
}
else if(item instanceof App.Item2){
playerClass = App.player2;
}
this.setPlayerView(playerClass);
}.observes('controller.item'),
setPlayerView: function(playerClass){
var v =this.get('childViews').find(function(item, index, enumerable){
return item instanceof App.basePlayer;
});
this.get('childViews').removeObject(v);
this.get('childViews').pushObject(playerClass.create());
}
Is this solution optimal or is there a better approach?
You can see an example here: