The event fires twice

I declare 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 create two instances of this view, as you can see here: http://cl.ly/H5WI

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

+7
source share
2 answers

After reading the comments, I think I already understand how I can help with your problem:

In your code, both views listen on the same global event, so both of them will respond simultaneously, and you want to be able to run selected() each view independently.

The usual approach for this is that the view is associated with the model, and the view listens for events on this model, so the events that are triggered for one model only affect the views associated with it.

This template is as follows:

 // 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 need to take care of triggering the selected event for each model when necessary.

Update

This template is so common that Backbone links the View.model link for you, so you can implement your View.initialize as follows:

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

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

Even if you reuse the link from the old instance of View to refer to the new instance of View, the old instance remains alive because there are still links to it.

This is a very common problem in Backbone, I think people are starting to call it "Ghosts Views".

To solve this problem, you must unbind all the events that View bind, in your example you can do:

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

Derick Bailey has a great article on this subject .

In addition, with humility, I want to relate one study about this issue . I tried to understand this tenacious behavior.

+1
source

All Articles