jsalonen
jsalonen

Reputation: 30481

Backbone.js `el` and `events` not binding properly

For some reason, while previously working just fine, have el and events bindings now stopped working properly.

I have had:

User.HeaderView = Backbone.View.extend({
    el: '#header',
    template: _.template($('#header-template').html()),
    events: {
        "click .login": "login"
    },
    initialize: function(parentView) {
        this.parentView = parentView;
    },
    render: function() {
        this.parentView.render();
        this.el.innerHTML = this.template(/* pass model */);
    }
});

Previously this worked just fine, but for some reason, el no longer correctly binds to #header in DOM. Instead, it is instantiated with empty div, which can be easily confirmed: if I debug el with Firebug (console.log(this.$el.parent().html()) I get:

null

What I'm expecting to get is something like:

<div id="header"><ul></ul></div>

This is the method I currently use to initialize the views:

view.headerView = new HeaderView(parentView);

Any ideas how I could fix this or debug further?

Upvotes: 1

Views: 1612

Answers (1)

nikoshr
nikoshr

Reputation: 33344

initialize expects an object containing the options you wish to pass to your view. Here you pass a view, which is an object and probably has an el attribute already set, overwriting the one you declare in HeaderView. Try

User.HeaderView = Backbone.View.extend({
    el: '#header',
    template: _.template($('#header-template').html()),
    events: {
        "click .login": "login"
    },
    initialize: function(options) {
        this.parentView = options.parentView;
    },
    render: function() {
        this.parentView.render();
        this.el.innerHTML = this.template(/* pass model */);
    }
});

new HeaderView({parentView:parentView});

Upvotes: 1

Related Questions