gpt4 book ai didi

javascript - 高级路由和单一对象定义?

转载 作者:行者123 更新时间:2023-11-28 02:44:25 25 4
gpt4 key购买 nike

我正在尝试简化路线。我现在仍然需要扩展路由器的类中的引用,但由于我使用 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

最佳答案

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

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

然后:

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

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

关于javascript - 高级路由和单一对象定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12136170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com