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.el
property should be defined as a jQuery selector (string), not a reference to HTML element.
From Backbone documentation:
var BodyView = Backbone.View.extend({
el: 'body'
});
Or as you wished,
el:'div#content'
When the view initializes, Backbone references the element in makes it available via the view.$el
property, which is a cached jQuery object.
this.$el.append("<p>Hello World</p>");
The sample code you posted works, because there is always only one body
element, and that element already exists in the DOM when your view is rendered. So when you declare el:$('body')
, you get a reference to the body element. The code in render
in works, because this.el is now a direct reference to the jQuery object:
(this.el).append("<p>Hello World</p>");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With