Troy Cosentino
Troy Cosentino

Reputation: 4778

backbone route cycling between routes before getting to the right one

What is the difference between these two methods of handling routes?

var Router = Backbone.Router.extend({
    routes: {'home': 'showHome}, 
    showHome: function() {//do whatever} 
});

and

var Router = Backbone.Router.extend({
    routes: {'home': 'showHome}, 
    initialize: function() { 
        var router = new Router(); 
        router.on('route:showHome', function(){//do something});
    }
});

Currently I have it the second way. It works fine and I get to the right places..

My router is now set up properly(I think) but my routes are still acting weird(as follows).

The only problem I am having is that when it goes to change a route the address bar flickers between multiple different routes before it lands on the right page (always gets to the right place).

I am changing pages be using window.location = '#/route'; inside of jQuery listeners inside of my views.

$('#right_arrow').live('click', {view: that}, this.rightArrow);
...
rightArrow: function(e){
    var that = e.data.view;
    if(typeof window.easyUserData.fbResponse.authResponse === 'undefined') {
        // Not logged in
        window.location = '#/login';
    } else {
        // Logged in
        window.location = '#/notes/right';
    }
    return false;
}

I have been trying to debug and what i have found when i set the breakpoint at window.location = '#/notes/right';:

  1. url changes properly ('#/notes/right')
  2. return false executes
  3. right arrow function ends and debugger goes into jquery code
  4. after five or six 'step over's in debugger (still in jquery code) url changes to '#/news/right', which is another route I use but not sure why it is coming up here
  5. after a few more 'step over' we get back to the original breakpoint where the url changes to the correct '#/notes/right'
  6. the new view loads

Why is it behaving like this? Is it related to how I have my router set up?

Upvotes: 0

Views: 97

Answers (1)

sma
sma

Reputation: 9597

Your code is instantiating a new Router in the initialize function, which is what is called when that particular object is instantiated to begin with. So essentially, you're creating an unnecessary router.

The code in the first example is correct. Then you simply do:

var myRouter = new Router();

Upvotes: 1

Related Questions