Skip to content

Instantly share code, notes, and snippets.

@max-mapper
Created April 26, 2012 03:56
Show Gist options
  • Save max-mapper/2495696 to your computer and use it in GitHub Desktop.
Save max-mapper/2495696 to your computer and use it in GitHub Desktop.
unobtrusive event binding
given some DOM:
<a href="#/">Foo<a>
<a href="#/bar">Bar<a>
<a href="#/baz!">Baz<a>
here is a relatively simple routing API:
var routes = {
'/': function() {
// triggered by <a href="#/">Foo<a>
},
'/:route': function(route) {
// triggered by <a href="#/bar">Bar<a>
},
modals: {
baz: function() {
// triggered by 'modal' routes, or <a> tags with hrefs that end in !
// e.g. <a href="#/baz!">Baz<a>
}
}
}
function catchModals( event ) {
var route = $(event.currentTarget).attr('href')
if (!route) return false
// Basic rules:
// * If the href ends with a bang (!) we're going to launch a modal
// * Otherwise, we're going to pass it through to Director
if ( route && route.indexOf( '!' ) === ( route.length - 1 ) ) {
route = route.replace('#/', '') // Trim off the #/ from the beginning of the route if it exists
route = route.substr(0, route.lastIndexOf('!'))
var id = route.split('/')[1] // The ID (if one exists) will be what comes after the slash
if (id) route = route.split('/')[0] // If there is an ID, then we have to trim it off the route
if (route in app.routes.modals) app.routes.modals[ route ](id)
if (_.isObject(event)) event.preventDefault()
} else {
redirect(route)
}
}
// Router comes from https://github.com/flatiron/director
Router(routes)
// catches <a href="#/baz!">Baz<a> and doesnt change window.document.href
$('a').live('click', catchModals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment