[英]Advanced routing and single object definition?
我正在嘗試簡化路線。 現在,我仍然需要在擴展router的類內使用引用,但是由於我使用eval
實例化引用,因此每個route方法都是相同的 。
目前,在我的應用程序內部:
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
我該怎么做?
正在運行: http : //franklovecchio-playback.herokuapp.com/?log = true
您可以使用兩個路由處理程序:
ROUTES =
'action1/:page': 'page'
'action2/:page': 'page'
'*path': 'def'
接着:
page: (page) ->
@setupPage(parseInt(page, 10))
def: ->
@setupPage(1)
splat路由( *path
)會將路由的匹配部分發送到處理程序,因此您不能僅使用一個路由處理程序而不嘗試解釋splat匹配的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.