Skip to content

Instantly share code, notes, and snippets.

@mhuebert
Created March 12, 2014 19:06
Show Gist options
  • Save mhuebert/9514013 to your computer and use it in GitHub Desktop.
Save mhuebert/9514013 to your computer and use it in GitHub Desktop.
urlPattern = require('url-pattern')
RouterMixin =
getInitialState: ->
match: this.match(this.props.path || window.location.pathname)
navigate: (path, callback) ->
window.history.pushState(null, null, path)
this.setState({ match: this.match(path) }, callback)
handleClick: (e) ->
if (e.target.tagName == 'A')
e.preventDefault()
this.navigate(e.target.pathname)
handlePopstate: ->
path = window.location.pathname
if this.state.match.path != path
this.setState match: this.match(path)
componentDidMount: ->
window.addEventListener 'popstate', this.handlePopstate
match: (path) ->
for route in (this.routes || [])
pattern = urlPattern.newPattern route.path
params = pattern.match(path)
if params
return {
path: path
params: params
handler: route.handler
}
getHandler: ->
this.state.match.handler
module.exports = RouterMixin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment