Reactgular
Reactgular

Reputation: 54771

Backbone View not selecting element

This is my first time create a view with Backbone, but I'm not able to render changes to an existing element in the document.

var ParamsView = Backbone.View.extend({

    el: $('#node-parameters'),

    initialize: function() {
        console.log('WOW');
    },

    render: function() {
        console.log('doing it');
        console.log(this.$el.length);
        console.log($('#node-parameters').length);
        this.$el.append('<span>hello world!</span>');
        return this;
    }

});

    var v = new ParamsView();
    v->render();

The words hello world! do not appear in the target div.

The console outputs the following when the view is rendered.

WOW
doing it
0
1

So I know that my jQuery selector $('#node-parameters') is finding 1 DOM element, but the view is not use it.

Any ideas what I'm doing wrong?

EDIT: In the JS debugger I can see that this.el is undefined for the view.

Upvotes: 1

Views: 1365

Answers (1)

nikoshr
nikoshr

Reputation: 33344

Your code is probably equivalent to this :

var ParamsView = Backbone.View.extend({
    el: $('#node-parameters'),

    initialize: function() {
        console.log('WOW');
    },

    render: function() {
        console.log('doing it');
        console.log(this.$el.length);
        console.log($('#node-parameters').length);
        this.$el.append('<span>hello world!</span>');
        return this;
    }
});

$(document).ready(function() {
    var v = new ParamsView();
    v.render();
});

http://jsfiddle.net/nikoshr/mNprr/

Notice that you class is declared before the DOM ready event.

You set the el at extend time with $('#node-parameters'). $ is a function that is immediately executed but, and that's why you get an undefined element, #node-parameters does not exist at that point.

By injecting the element with new ParamsView({el: '#node-parameters'}), you set a valid el after the DOM ready event. You could also set it via

var ParamsView = Backbone.View.extend({
    el: '#node-parameters'
});

el is then evaluated when you instantiate your class, after the DOM ready event. http://jsfiddle.net/nikoshr/mNprr/1/

Upvotes: 2

Related Questions