Skip to content

Instantly share code, notes, and snippets.

@issm issm/router.coffee
Created May 2, 2013

Embed
What would you like to do?
class @Router
constructor: (params = {}) ->
@_rules = []
for k, v of params.connect ? {}
@connect(k, v)
connect: (hash, action) ->
@_rules.push( hash: hash, action: (action ? ->) )
return @
match: (url_hash, ev) ->
ret = null
url_hash = url_hash.replace( /^.*\#!?/, '' ) # '#' or '#!' を含む以前を削除
for r in @_rules
{hash: h, action: a} = r
m = url_hash.match( @_build_regexp(h) )
if m?
ret = (o) ->
m.shift()
return a.apply(o, [m, ev])
break
if !ret?
ret = (o) =>
return @_cannot_route.apply(o, [url_hash, ev])
return ret
_build_regexp: (h) ->
return new RegExp( ("^#{h}$").replace(/^\^+/, '^').replace(/\$+$/, '$') )
_cannot_route: (h, ev) ->
throw new Error('cannot route: ' + h)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.