I have a problem with my router not redirecting when i call navigate.
Im running a Rails setup with the ‘backbone-on-rails’ gem.
The problem seems to be related to how the app is initialised.
App
window.App =
Models: {}
Collections: {}
Views: {}
Routers: {}
initialize: ->
new App.Routers.Main()
Backbone.history.start({pushState: true})
$ ->
App.initialize()
Router
class App.Routers.Main extends Backbone.Router
routes:
'': 'index'
'login': 'login'
initialize: ->
# Check login status
@check_login_status()
initialize_layout: ->
# Default layout template
layout = new App.Views.Layout
$('#main').html( layout.render().el )
# Navigation template
navigation = new App.Views.Navigation(user: @current_user)
$('#main nav[role="top"]').html( navigation.render().el )
# Return this
this
index: ->
@initialize_layout() unless @current_user.get('company_id') is null
this
login: ->
layout = new App.Views.Layout
$('#main').html( layout.render().el )
login = new App.Views.Login
$('#main .container-fluid').html(login.render().el)
check_login_status: ->
@current_user = new App.Models.CurrentUser
@current_user.fetch({
async: false
success: (data, status, xhr) ->
# If no user is logged in, and we arent on the login page, redirect to it
if data.get('company_id') is null and window.location.pathname isnt '/login'
# Navigate to login page
window.location.href = '/login'
})
In my router i have an initialise function that checks wether or not the user is logged in. I console.log a simple status to easily verify it, and indeed it logs out ‘not logged in’.
Despite that, the navigate doesnt redirect to /login.
If i start backbone history before i start the router, then the navigate part works, but when i refresh the page (cmd+r) then the router doesn’t run the index method.
The reason the navigation to
/logindoesn’t trigger the routeloginis the leading forward slash. If you leave out the forward slash, it should work:Forward slash -prefixed URL means that the route should be found at the domain’s root, i.e.
domain.com/login. To maintain the flexibility to run your application in a URL that’s not in the application’s root, say,domain.com/en/login, you should prefer the relative URL format.You also say:
This is probably not a good idea. I don’t know exactly how it “works”, but the Backbone documentation is quite clear on this topic: