Event fires twice

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?


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

As you have declared two instances of VirtualFileSelectorView you have two observers of the event selected.

Even if you are reusing the reference of the old View instance to make reference to the new View instance the old instance remains alive because there is still references targeting to it.

This is a very common issue in Backbone, I think people is starting to call it "ghosts Views".

To solve this you have to unbind all the events that the View is binding, in your example you can do:

app.virtualFileSelectorView.off( null, null, this );

Derick Bailey has an excellent post about this matter.

Also, with humility, I want to link to one study about this matter I did to try to understand this tenacious behavior.

链接地址: http://www.djcxy.com/p/10814.html

上一篇: Safari(Mac OS X Lion)将错误的epochtime值返回给position.timestamp调用

下一篇: 事件发生两次