Kelly Jr. Kelly Jr. - 1 year ago 80
Javascript Question

backbone this.$el undefined

Not sure what's wrong with my code. this.$el is undefined within my render method?

var Person = Backbone.Model.extend({
defaults: {
name: 'John',
age: 30,
occupation: 'worker'
}
});

var PersonView = Backbone.View.extend({
initialize: function(){
this.render();
},

render: function(){
tagName:'div',
console.log(this.$el) // undefined?
//var html = this.$el.html( this.model.get('name') );
//$('here').html(html);
}
})

var p = new Person();
var pv = new PersonView({model: p});


http://jsfiddle.net/p6522o0n/

Answer Source

A few things:

  1. The tagName property definition is in the render function and not the view declaration. I'm guessing that's a copy paste error. (Just move tagName: 'div', up a line and you're good--or just remove it, since 'div' is the default)

  2. The problem is that you're using an ancient version of backbone (0.5.3). This version does not put an $el property on the view. But you can inspect the view and you'll see that the el property is there and all correct. Upgrading to backbone 1.3.3 fixes it but also requires an underscore upgrade.

So your options are:

  1. Upgrade Backbone

  2. Put this line in your view's initialize function:

this.$el = $(this.el)

You could even create a base view class that all your views will inherit from that does this automatically.

Here's a fiddle with the upgraded versions.

Here's a fiddle with the second fix.