Riccardo
Riccardo

Reputation: 373

Backbone router.navigate doesn't redirect

Honestly I feel a bit stupid asking this question because should be a very simple thing... In my app init, I have:

window.myApp =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  initialize: ->
    window.router = new Backbone.Router

    Backbone.history.start(pushState: true)

And then in my View, when I click a button, I do:

router.navigate('/profile')

I have tried also with

router.navigate('/profile', true)

Now...I know that this isn't the best way of use backbone routes, but I need that my rails app manage the routes and I use backbone routes only for have routes history... If I do window.href = '/profile' it redirects correctly.

What I'm doing wrong with backbone routes ? I've used this way time ago, but I don't find out why now it doesn't work anymore.

EDIT: The new url is always correctly show in the navigation bar, but it doesn't redirect to the new page...only show the new url in the navigation bar.

Upvotes: 1

Views: 4080

Answers (2)

Telmo Dias
Telmo Dias

Reputation: 4168

We had an issue with this, and found out that sometimes even window.location.href does not work.

We were lucky to find this post Backbone: Refresh the same route path for twice and we were actually only able to make it work using a combination of the presented solution :

  1. Navigate to an inexistent route : Backbone.history.navigate('xpto');

  2. Then use: window.location.href = location;

Upvotes: 0

user229044
user229044

Reputation: 239260

Backbone router.navigate doesn't redirect

No, it doesn't. That's not what router.navigate even does. It's has nothing to do with redirecting, it's for updating the address bar.

The new url is always correctly show in the navigation bar, but it doesn't redirect to the new page...only show the new url in the navigation bar.

Yes, this is exactly what router.navigate is documented to do. That is its express purpose. You use it to update the URL to reflect the current state of the page, not to redirect the page to something else.

If you want to redirect to a new page, you're supposed to use window.location.href = '/profile'.

If you want to update the address bar and then trigger a fresh round of Backbone routing, use router.navigate('/profile', { trigger: true });, but again, that's not how Backbone is meant to work.

Upvotes: 4

Related Questions