Skip to content

Instantly share code, notes, and snippets.

@issm
Created May 2, 2013 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save issm/5499966 to your computer and use it in GitHub Desktop.
Save issm/5499966 to your computer and use it in GitHub Desktop.
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