Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event triggered multiple times after using back button in Backbone.js

I'm building a Backbone app and I came across this weird issue. In the state A (route: ""), I've got a view like that:

var view = Backbone.View.extend({
    events : {
         "click a.continue" : "next"
    },

    next : function(e) {
       //Some stuff
       Backbone.history.navigate("/page2");
    }
});

and once I click on the anchor with "continue" class, I am redirected to a state B (route: "/page2"). If I click on the back button of my browser, and then I click on the anchor, debugging I've noticed that the next function is triggered twice. Actually if I keep going back and forth the number of times the event is triggered keeps increasing.

Any clue?

like image 872
sebarmeli Avatar asked Nov 18 '25 03:11

sebarmeli


1 Answers

You've got a zombie view hanging around.

The gist of it is that when you are instantiating and displaying the second view ("state B"), you are not disposing of the first view. If you have any events bound to the view's HTML or the view's model, you need to clean those up when you close the form.

I wrote a detailed blog post about this, here: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

Be sure to read the comments as "Johnny O" provides an alternative implementation which I think is quite brilliant.

like image 100
Derick Bailey Avatar answered Nov 20 '25 19:11

Derick Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!