1

我正在尝试简化路线。我现在仍然需要在扩展路由器的类中进行引用,但是由于我eval用于实例化引用,因此每个路由方法都是相同的

目前,在我的应用程序中:

ROUTES =
  'action1/:page': 'action1'
  'action2/:page': 'action2'
  '*path': 'default' # Default routes to action1

# Start Backbone history.
App.Router = new Routes(
  routes: ROUTES
)
App.Router.setDefaultRoute 'action1'
Backbone.history.start()

和路由器类:

class window.Routes extends Backbone.Marionette.AppRouter

  constructor: (options) ->

    @on 'all', @storeRoute
    @history = []
    super options

  @trace initialize: () ->

    debug.info 'Routes: ' + JSON.stringify @routes

  @trace setDefaultRoute: (route) ->

    App.Data.defaultRoute = route

  @trace getDefaultRoute: () ->

    App.Data.defaultRoute

  @trace storeRoute: () ->

    @history.push Backbone.history.fragment

  @trace getPrevious: () ->

    if @history.length > 1
      @history[@history.length - 1] 

  @trace getPreviousRoute: () ->

    @getPrevious().split('/')[0]

  @trace getPreviousPage: () ->

    @getPrevious().split('/')[1]

  @trace getFormattedWindowHash: () ->

    hash = window.location.hash
    hash = hash.substring(1, hash.length) 

    hash

  @trace getCurrentRoute: () ->

    current = @getFormattedWindowHash().split('/')[0]

    # Allow us to not specify 'route = <route>' inside every routing method.
    if !current
      current = @getDefaultRoute()
    else
      current = current

    current = current.charAt(0).toUpperCase() + current.slice(1)    

  @trace getCurrentPage: () ->

    @getFormattedWindowHash().split('/')[1]

  # Everytime a page is loaded, default data is cleared by instantiating new 
  # Views, Events, UI, State, and Error classes.
  @trace setupPage: (page) ->

    route = @getCurrentRoute()

    debug.info 'current route: ' + route

    event = 'App.Pages.Events.' + route + ' = new App.Events.' + route + '()'
    debug.info 'eval event: ' + event

    eval event

    # The magic which routes to the page.
    goTo = 'App.Pages.Events.' + route + '.router(parseInt(' + page + '))'
    debug.info 'goTo: ' + goTo

    eval goTo

  # Place routing actions below.

  @trace action1: (page) ->

    @setupPage page

  @trace action2: (page) ->

    @setupPage page

  # Default route.
  @trace default: () ->

    # TODO make this settable?
    @action1 1

我想要做的是能够删除这 3 种方法:

 @trace action1: (page) ->

    @setupPage page

  @trace action2: (page) ->

    @setupPage page

  # Default route.
  @trace default: () ->

    # TODO make this settable?
    @action1 1

我怎样才能做到这一点?

运行: http: //franklovecchio-playback.herokuapp.com/?log =true

完整代码:https ://github.com/franklovecchio/playback

4

1 回答 1

1

您可以使用两个路由处理程序:

ROUTES =
  'action1/:page': 'page'
  'action2/:page': 'page'
  '*path': 'def'

接着:

page: (page) ->
  @setupPage(parseInt(page, 10))
def: ->
  @setupPage(1)

splat 路由 ( *path) 会将路由的匹配部分发送到处理程序,因此您不能只使用一个路由处理程序而不尝试解释 splat 匹配的内容。

于 2012-08-27T05:03:40.703 回答