Skip to content

Instantly share code, notes, and snippets.

@danmartens
Created August 31, 2012 17:51
Show Gist options
  • Save danmartens/3556480 to your computer and use it in GitHub Desktop.
Save danmartens/3556480 to your computer and use it in GitHub Desktop.
FTW Router
hasPushState = !!(window.history && window.history.pushState)
window.FTW or= {}
class FTW.Router
constructor: (@routes) ->
if hasPushState
window.onpopstate = (e) =>
@navigate(@getURI())
getURI: ->
if hasPushState
return location.href.replace(/http:\/\/.*\//, '')
else
return location.hash.replace('#', '')
setURI: (uri) ->
if hasPushState
history.pushState({}, null, '/' + uri.replace(/^\//, ''))
else
location.hash = uri
buildURI: (route, params) ->
for p in route.match(/:[a-z0-9_]*/gi)
value = params[p.replace(':', '')]
if value
route = route.replace(p, value)
return route
parseURI: (uri, route) ->
params = {}
for s, i in route.split('/')
if s.indexOf(':') == 0
params[s.replace(':', '')] = uri.split('/')[i]
return params
matchesRoute: (uri, route) ->
for s, i in route.split('/')
unless s.indexOf(':') == 0
unless uri.split('/')[i] == s
return false
return true
navigate: (uri) ->
for route, func of @routes
if @matchesRoute(uri, route)
@setURI(uri)
return func(@parseURI(uri, route))
return false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment