Skip to content

Instantly share code, notes, and snippets.

@aerith
Created March 1, 2012 07:40
Show Gist options
  • Save aerith/1948074 to your computer and use it in GitHub Desktop.
Save aerith/1948074 to your computer and use it in GitHub Desktop.
dispatcher =
location: window.location
stash: []
connect: (paths, action) ->
if paths or paths is 0
paths = paths.valueOf()
# webkit: typeof RegExp is function
if typeof paths is 'object' and not paths instanceof RegExp
paths = { pathname: paths }
@.stash.push [paths, action]
@
and: () ->
stash = @.stash
length = stash.length
length[length - 1][2] = true if length > 0
@
dispatch: (location) ->
location = if location then location else dispatcher.location
stash = @.stash
params = {}
for data in stash
paths = data[0]; action = data[1]; chain = data[2]
matched = false
for key in paths
continue unless paths.hasOwnProperty(key) and paths[key]
continue unless location[key]
value = paths[key]; path = location[key]
result = @.match(value, path)
matched = !!result
break unless matched
params[key] = result
if matched
action? and action(params)
break unless chain
@.clear()
@
match: (value, path) ->
if value instanceof RegExp
result = value.exec(path) or false
else
value = value.toString()
result = path.indexOf(value) isnt -1 and value
result
clear: () ->
@.stash = []
@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment