sebarmeli
sebarmeli

Reputation: 18275

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?

Upvotes: 3

Views: 4643

Answers (2)

vlycser
vlycser

Reputation: 408

I Have the same problem, the solution is...

    App.Router = Backbone.Router.extend({
    routes: {
        "fn1": "fn1",
        "fn2": "fn2"
    },
    stopZombies: function(objView){
        if(typeof objView === "object"){
            objView.undelegateEvents();
            $(objView.el).empty();
        }
    },
    fn1: function(){

        this.stopZombies(this.lastView);

        var view1 = new App.v1();
        this.lastView = view1;
    },
    fn2: function(){

        this.stopZombies(this.lastView);

        var view2 = new App.v2();
        this.lastView = view2;
    }
});

Store the last execute view in this.lastView, then stopZoombies() remove the events from this view.

Upvotes: 4

Derick Bailey
Derick Bailey

Reputation: 72868

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.

Upvotes: 10

Related Questions