Under the hood, Backbone uses jQuery's "delegate" to wire up the events. So it's not that this is "like" jQuery, it is jQuery doing it for us.
To prevent scoping problems and ensure that our View events are only working with the HTML/DOM elements that we want, all events
declarations are scoped to the View's el
.
When a Backbone view is instantiated, an el
attribute is either generated for you, or assigned by you. This gives you the opportunity to either attach your view to an existing chunk of the DOM or to create a new chunk of HTML that can be attached to the DOM.
Here's how you can attach to the existing DOM:
MyView = Backbone.View.extend({
// ...
});
var existingDomEl = $("#someElement");
new MyView({
el: existingDomEl
});
By specifying the el
when we instantiate the view, or by specifying it directly in our view definition, we use an existing element.
If we omit the el
from the constructor options and from the view definition, Backbone will generate an el
for us. By default it will generate a div in el
when the view is instantiated.
Once a View has it's el
, whether through generation or assignment, the view's event declarations are delegated via jQuery, scoped to the view's el
.
let's say you have the following html:
<div id="foo">
<button class="btnSay">Say!</button>
</div>
<div id="bare">
<button class="btnSay">Say, Part 2!</button>
</div>
with your example View, we could assign a view to either the foo
or the bar
element, and only the button within that element would get the click event.
var PersonView = Backbone.View.extend({
....
events : {
"click button.btnSay" : "saySomething"
},
saySomething : function(){
....
}
...
});
new PersonView({
el: $("#foo")
});
Now when you click the button in the foo
div, you'll get the saySomething
callback fired. But because the events for PersonView were scoped within the el
for that instance of PersonView, clicking the button within bar
will never fire the callback.