我正在尝试简化路线。我现在仍然需要在扩展路由器的类中引用,但由于我使用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()
和Router类:
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
我该如何做到这一点?
答案 0 :(得分:1)
您可以使用两个路由处理程序:
ROUTES =
'action1/:page': 'page'
'action2/:page': 'page'
'*path': 'def'
然后:
page: (page) ->
@setupPage(parseInt(page, 10))
def: ->
@setupPage(1)
splat路由(*path
)会将路由的匹配部分发送给处理程序,因此您不能仅使用一个路由处理程序而不尝试解释splat匹配的内容。