I seem to have a problem with the code below. I have a div element with the id=’content’ in my html. I wanted to replace ‘body’ element of el property with the div element but my hello world text doesn’t when I typed el: $(‘div’) or el:$(‘div#content’) or el: $(‘#content’). I’m a beginner in backbone.js and in my understanding, I believe that this el property holds our parent tag where all our templates will be added as child elements(in this case ‘body’ tag being parent and ‘p’ tag being child).
(function($){
var ListView = Backbone.View.extend({
el: $('body'),
initialize: function(){
this.render();
},
render: function(){
(this.el).append("<p>Hello World</p>");
}
});
var listView = new ListView();
})(jQuery);
The
View.elproperty should be defined as a jQuery selector (string), not a reference to HTML element.From Backbone documentation:
Or as you wished,
When the view initializes, Backbone references the element in makes it available via the
view.$elproperty, which is a cached jQuery object.The sample code you posted works, because there is always only one
bodyelement, and that element already exists in the DOM when your view is rendered. So when you declareel:$('body'), you get a reference to the body element. The code inrenderin works, because this.el is now a direct reference to the jQuery object:If you need to initialize a Backbone view using an existing DOM element (not a selector), Backbone documentation recommends passing it in the initialize function.