Reputation: 4458
I have a model's view set up as follows:
var PlayerView = Backbone.View.extend({
el: "div.player",
template: _.template($("#playerTemplate").html()),
render: function() {
this.$el.append(this.template(this.model.toJSON()));
return this;
}
});
and the main view is set up as follows:
var AppView = Backbone.View.extend({
el: "#players",
render: function() {
var pView = new PlayerView({model: playerModel});
this.$el.append(pView.render().$el);
}
});
If you notice the render
of AppView
, I am rendering the PlayerView
first, and then appending its $el
to AppView
's $el. I was expecting an error situation here, as it would display PlayerView
2 times to main View as follows:
pView.render()
where I put content in pView
and$el
to main view.But it just appends the pView
only once. How does this work?
I am not sure I have explained my question clearly; I can add more context if required.
Upvotes: 0
Views: 193
Reputation: 43156
Assuming div.player
exists in DOM as you mentioned in comments,
When you do pView.render()
, it adds the template inside it.
Then when you append pView
's element (div.player
) to AppView's element (#players
), entire div.player
is moved into #players
.
Your code is working the way it should work.
If you intent to create multiple players, You shouldn't use el
option in player view, Instead you should decorate the element created by backbone and create multiple instances of player view.
Upvotes: 2