Search code examples
javascriptbackbone.js

Backbone View instance not working as expected


I think I am missing something very trivial here. I have created a Backbone View as follows(without extending Backbone.View):

var PlayersView = new Backbone.View({
    initialize: function() {
        this.render();
    },
    render: function() {
        console.log("hello World");
    }
});

But it doesn't log anything when I run this code. It doesn't work when I explicitly do: PlayersView.render(); as well.

But the following code works :

var PlayersView = Backbone.View.extend({
    initialize: function() {
        this.render();
    },
    render: function() {
        console.log("hello World");
    }
});

var playersview = new PlayersView();

Solution

  • The View constructor does not accept properties to add to the constructed object. It accepts a few special options like 'model', 'tagName', and so on. But the initialize(...) and render(...) properties in your first code snippet are effectively ignored.

    The proper way to provide initialize, render, is to use Backbone.View.extend({...}).