Note that there are some explanatory texts on larger screens.

plurals
  1. POproper way to dynamically assign backbone.js view el
    text
    copied!<p>I would like to create two ( or more ) view instances, each with different el attributes, and have events bound to them via backbone.js view's events hash ( not through jQuery ).</p> <p>Getting events to trigger when all instantiations have the same <code>el</code> is easy:</p> <pre><code>someView = Backbone.View.extend({ el: '#someDiv', events: { 'click': 'someFunction' }, someFunction: function(){ //Do something here } }); </code></pre> <p>So far, if I assign <code>el</code> in the <code>initialize</code> function, and set <code>events</code> normally as follows, events do not trigger:</p> <pre><code>someView = Backbone.View.extend({ events: { 'click': 'someFunction' }, initialize: function( options ){ this.el = options.el }, someFunction: function(){ //Do something here } }); </code></pre> <p>My first instinct was to have <code>el</code> be a function that returns the string representation of the dom element of interest:</p> <pre><code>someView = Backbone.View.extend({ el: function(){ return '#someDiv-' + this.someNumber }, events: { 'click': 'someFunction' }, initialize: function( options ){ this.someNumber = options.someNumber }, someFunction: function(){ //Do something here } }); </code></pre> <p>However, this triggers <code>someFunction</code> x times if I have x instantiations of <code>someView</code>.</p> <p>Next I tried setting both the <code>el</code> and <code>events</code> attributes in <code>initialize</code>:</p> <pre><code>someView = Backbone.View.extend({ initialize: function( options ){ this.el = options.el this.events = { 'click': 'someFunction' } }, someFunction: function(){ //Do something here } }); </code></pre> <p>but this does not trigger events. At this point I'm pretty much fishing.</p> <p>Does anyone know how instantiate a backbone.js view with an <code>el</code> specific to that instance that has events that only trigger for that instance, and not other instances of the <code>View</code>?</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