Doing my best to learn BackboneJS. I was told that "el" is special. However, looking at the code below, looks like I can use any property name I like. For example:
MyEL : $('body')
then I'm going to use it this way
$(this.MyEL).append("<ul></ul>");
Am I violating if I don't use el? Am I breaking something?
(function($){
var ListView = Backbone.View.extend({
el: $('body'), // el attaches to existing element
myEL: $('body'), // myEL attaches to existing element
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here
this.counter = 0; // total number of items added thus far
this.render();
},
// `render()` now introduces a button to add a new list item.
render: function(){
// $(this.el).append("<button id='add'>Add list item</button>");
// $(this.el).append("<ul></ul>");
$(this.myEL).append("<button id='add'>Add list item</button>");
$(this.myEL).append("<ul></ul>");
},
// `addItem()`: Custom function called via `click` event above.
addItem: function(){
this.counter++;
$('ul', this.el).append("<li>hello world"+this.counter+"</li>");
}
});
var listView = new ListView();
})(jQuery);
If you look at the code, what you're doing is extending (Backbone.View.extend({//options})
) the default backbone view object with whatever properties you wish to add. If you pass a property that exists by default in backbone view, it'll be overwritten with the value you pass.
By default all backbone views have an el
property. If you don't explicitly pass it's value in options, backbone will create a <div>
and assign it to the el
property.
When you pass el: $('body')
in the options, backbone will point the default el
property to <body>
and won't create a <div>
.
By passing myEL: $('body')
in the options, you've creating a property in the view object called myEL
which points to <body>
element, which in this case seems quite unnecessary.