For the given example, what is the difference between this.el
& this.$el
I understand that this.$el
points to the jQuery object of this.el
, which in this case is 'li'
.
When I render a view, I can choose between this.el
, or this.$el
. How am I able to render something to a page when I reference the jQuery object? I can see how using this.$el.html(property)
, points to the html, but why appending this.$el
and having it render is what confuses me.
var Person = Backbone.Model.extend({
defaults: {
name: 'John Doe',
age: 30,
occupation: 'worker'
}
});
var PersonView = Backbone.View.extend({
tagName: 'li',
initialize: function() {
this.render();
},
render: function() {
var out = this.$el.html(this.model.get('name') + this.model.get('occupation'));
console.log(this, this.el, this.$el, out);
$('body').append(this.$el);
},
});
var person = new Person;
var personview = new PersonView({model: person});
Bojangles is correct.
this.$el
is a reference to the element in the context of jQuery, typically for use with things like.html()
or.addClass()
, etc. For example, if you had a div with idsomeDiv
, and you set it to theel
property of the Backbone view, the following statements are identical:this.$el.html()
$("#someDiv").html()
$(this.el).html()
this.el
is the native DOM element, untouched by jQuery.