【问题标题】:Backbone router.navigate doesn't trigger骨干 router.navigate 不会触发
【发布时间】:2013-01-30 12:04:37
【问题描述】:

当我调用导航时,我的路由器没有重定向。

我正在使用“backbone-on-rails”gem 运行 Rails 设置。

问题似乎与应用程序的初始化方式有关。

应用

window.App =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  initialize: ->
    new App.Routers.Main()
    Backbone.history.start({pushState: true})

$ ->
  App.initialize()

路由器

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'

    })

在我的路由器中,我有一个初始化功能,用于检查用户是否已登录。我 console.log 一个简单的状态以轻松验证它,实际上它会注销“未登录”。

尽管如此,导航不会重定向到 /login。

如果我在启动路由器之前启动主干历史记录,那么导航部分可以工作,但是当我刷新页面 (cmd+r) 时,路由器不会运行索引方法。

【问题讨论】:

    标签: ruby-on-rails backbone.js coffeescript


    【解决方案1】:

    导航到/login 不会触发路由login 的原因是前导正斜杠。如果您省略正斜杠,它应该可以工作:

    self.navigate('login', {trigger: true})
    

    以正斜杠为前缀的 URL 表示应该在域的根目录下找到路由,即domain.com/login。为了保持在不在应用程序根目录中的 URL(例如 domain.com/en/login)中运行应用程序的灵活性,您应该更喜欢相对 URL 格式。

    你还说:

    在我启动路由器之前启动主干历史,然后导航部分工作

    这可能不是一个好主意。我不确切知道它是如何“工作”的,但Backbone documentation 在这个话题上非常清楚:

    在页面加载期间,在您的应用程序完成所有路由器的创建后,请务必调用 Backbone.history.start() 或 Backbone.history.start({pushState: true})路由初始 URL。

    【讨论】:

    • 感谢您的回答。是的,我也在文档中发现了关于历史的部分。目前我做了一个 location.href 但感觉不对。必须有一种对骨干更友好的方式。更新了代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多