proper way to dynamically assign backbone.js view el

Posted by kikuchiyo on Stack Overflow See other posts from Stack Overflow or by kikuchiyo
Published on 2012-06-26T15:12:23Z Indexed on 2012/06/26 15:15 UTC
Read the original article Hit count: 316

Filed under:

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 ).

Getting events to trigger when all instantiations have the same el is easy:

someView = Backbone.View.extend({
  el: '#someDiv',

  events: {
    'click': 'someFunction'
  },

  someFunction: function(){
    //Do something here
  }
});

So far, if I assign el in the initialize function, and set events normally as follows, events do not trigger:

someView = Backbone.View.extend({
  events: {
    'click': 'someFunction'
  },

  initialize: function( options ){
    this.el = options.el
  },

  someFunction: function(){
    //Do something here
  }
});

My first instinct was to have el be a function that returns the string representation of the dom element of interest:

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
  }
});

However, this triggers someFunction x times if I have x instantiations of someView.

Next I tried setting both the el and events attributes in initialize:

someView = Backbone.View.extend({

  initialize: function( options ){
    this.el = options.el
    this.events = {
      'click': 'someFunction'
    }
  },

  someFunction: function(){
    //Do something here
  }
});

but this does not trigger events. At this point I'm pretty much fishing.

Does anyone know how instantiate a backbone.js view with an el specific to that instance that has events that only trigger for that instance, and not other instances of the View?

© Stack Overflow or respective owner

Related posts about backbone.js