Created
May 2, 2013 03:24
-
-
Save issm/5499966 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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