Search code examples
backbone.jsbackbone-routing

Backbonejs - router initializing function calls 3 times - on navigation change


In my app, I have main link and sub links, so each of the link change, i am calling the appropriate function.

so, each time the router change, i need to call my navigation function do this, i did like this:

var appRouters = Backbone.Router.extend({
        routes:{
            "general/":"defaultRoute",
            "general/:page/":"generalSublinks",
            "repositories/":"repositories",
            "repositories/:page/":"repositoriesSublinks",
            "savedSearch/":"savedSearch",
            "favourites/":"favourites",
            "reports/":"reports",
            "preferences/":"preferences",
            "preferences/:page/":"preferencesSubLinks",
            '*path':  'defaultRoute'
        },
        initialize:function(){
            this.bind("all", this.navigationUpdate); // calling 3 times each navigation change.. how to solve this?
        },
        navigationUpdate:function(){
            new naviView();
        },
        defaultRoute:function(){
            new dBView();
        },
        generalSublinks:function(id){
            if(id === "dashBoard"){
                this.defaultRoute();
            }else if(id === "myTask"){
                new myTaskView();
            }else if (id === "myDocument"){
                new myDocView();
            }else if (id === "myTemplate"){
                new myTempView();
            }else if (id === "search"){
                new mySearchView();
            }
        }

});

it works fine. But i am getting the navigationUpdate - called as 3 times. any idea to solve this pelase..?


Solution

  • This is because you are listening to all.

    Try adding this to see what events you are picking up:

        navigationUpdate:function(eventName){
             console.log(eventName);
             new naviView();
        }
    

    To fix it, you should be able to do this:

    this.on("route", this.navigationUpdate, this);