Event fires twice

marcus picture marcus · Jun 3, 2012 · Viewed 7.6k times · Source

I'm declaring a View like this:

var VirtualFileSelectorView = Backbone.View.extend({
    selected: function() {
        console.log("selected function");
    },

    initialize: function() {
        // Shorthand for the application namespace
        var app = brickpile.app;
        // bind to the selected event
        app.bind('selected', this.selected, this);
    }
});

Then I instantiate two instances of this View like you can see here: http://cl.ly/H5WI

The problem is that when the event selected is fired the function selected is called twice?

Answer

fguillen picture fguillen · Jun 4, 2012

After read the comments thread I think I already understand how can I help with your issue:

In your code both Views are listening to the same global event, so both of them will respond at the same time, and you want to be able to trigger the selected() of each View in independent.

The usual approach to do this is that a View is associated with a Model, and the View is listening to the events on that Model, so events triggered for one Model only will affect to Views associate to it.

This pattern looks like this:

// code simplified and not tested
var MyView = Backbone.View.extend({
  initialize: function( opts ){
    this.model = opts.model;
    this.model.on( "selected", this.selected, this );
  },

  selected: function( model ){
    // ...
  }
})

var oneModel = new MyModel();
var oneView = new MyView({ model: oneModel });

Now you only have to take care of trigger the selected event on each Model when is needed.

Updated

This pattern is so common that Backbone associates the View.model reference for you so you can implement your View.initialize like this:

initialize: function(){
  this.model.on( "selected", this.selected, this );
}