Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You don't actually need to go through all that "this.element" stuff.</p> <p>Backbone automatically sets the view's "el" to the "el" you pass into the constructor as an option.</p> <p>It is then available as "this.el" throughout the view.</p> <p>This is all you need to do:</p> <pre><code>x = Backbone.View.extend({ events: { 'click': 'say_hi' }, initialize: function( options ){ // Not actually needed unless you're doing something else in here }, say_hi: function(){ alert( this.el.id ); } }); y = new x( {el: '#div-1'} ); z = new x( {el: '#div-2'} ); z.say_hi(); y.say_hi(); ​ </code></pre> <p>See this live jsFiddle: <a href="http://jsfiddle.net/edwardmsmith/QDFwf/15/" rel="noreferrer">http://jsfiddle.net/edwardmsmith/QDFwf/15/</a></p> <p>The reason your second example did not work is that with the latest versions of Backbone, you cannot just set the "el" directly any more. This does not, as you noticed, properly set/update events.</p> <p><strong>Does not work</strong></p> <pre><code>initialize: function( options ){ this.el = options.el; } </code></pre> <p>If you wanted to set the el dynamically that way, you need to use <a href="http://backbonejs.org/#View-setElement" rel="noreferrer">View.setElement</a> as that properly delegates events and sets up the cached <a href="http://backbonejs.org/#View-$el" rel="noreferrer">this.$el</a>.</p> <p><strong>Works</strong></p> <pre><code>initialize: function( options ){ this.setElement(options.el) } </code></pre> <p>Live jsFiddle of your second example: <a href="http://jsfiddle.net/edwardmsmith/5Ss5G/21/" rel="noreferrer">http://jsfiddle.net/edwardmsmith/5Ss5G/21/</a></p> <p>But this is just re-doing what is already being done under the hood in Backbone.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload