Working through the setElement part of Addy Osmani's backbone.js tutorial.
He presents this example:
// We create two DOM elements representing buttons
// which could easily be containers or something else
var button1 = $('<button></button>');
var button2 = $('<button></button>');
// Define a new view
var View = Backbone.View.extend({
events: {
click: function(e) {
console.log(view.el === e.target);
}
}
});
// Create a new instance of the view, applying it
// to button1
var view = new View({el: button1});
// Apply the view to button2 using setElement
view.setElement(button2);
button1.trigger('click');
button2.trigger('click');
However, he doesn't explain why there is different output for button1.trigger('click'); vs. button2.trigger('click'); -- possibly a dumb question, and I know that these are different ways of attaching the view to the button elements, but why does button2.trigger('click'); also return true?
button1.trigger('click');shouldn't produce any output at all from that code.setElementis fairly simple:So
view.setElement(e)does four things:eventsfromview.el.view.el = e.view.$el = Backbone.$(e).eventsto the newview.el.The result is that nothing will be left listening to events from
button1andviewwill be listening to events frombutton2.A more thorough example might help so let us attach some more click event handlers:
Demo: http://jsfiddle.net/ambiguous/S7A9z/
That should give you something like this in the console:
Both raw jQuery event handlers will be triggered as expected but we'll only get the
button2event through Backbone because thesetElementcall happened before thetriggercalls.So why is
view.el === e.targettrue? Well, you're clicking onbutton2soe.targetwill bebutton2and theview.setElement(button2)call replacesview.elsothis.elinside the Backboneclickhandler will also bebutton2.