software_writer
software_writer

Reputation: 4458

How does Backbone View render work?

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:

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

Answers (1)

T J
T J

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

Related Questions