Created
August 24, 2011 00:21
-
-
Save tj/1166989 to your computer and use it in GitHub Desktop.
example of backbone-style routing with Express
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
app.get('/help', function(req, res){ | |
res.send('some help'); | |
}); | |
app.get('/search/:query/p:page', function(req, res){ | |
var query = req.params.query | |
, page = req.params.page; | |
res.send('search "' + query + '", page ' + (page || 1)); | |
}); |
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
function Router(obj) { | |
this.methods = obj; | |
this.route(obj.routes); | |
} | |
Router.prototype.route = function(obj){ | |
var self = this | |
, routes = Object.keys(obj); | |
Object.keys(obj).forEach(function(route){ | |
var parts = route.split(' ') | |
, method = parts.shift().toLowerCase() | |
, path = parts.shift() | |
, fn = self.methods[obj[route]]; | |
app[method]('/' + path, function(req, res, next){ | |
var args = req.route.keys.map(function(key){ | |
return req.params[key.name]; | |
}); | |
fn.apply(res, args); | |
}); | |
}); | |
}; | |
Router.extend = function(obj){ | |
return new Router(obj); | |
}; |
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
// GET /help | |
// GET /search/foobar | |
// GET /search/foobar/p2 | |
var router = Router.extend({ | |
routes: { | |
'GET help': 'help' | |
, 'GET search/:query': 'search' | |
, 'GET search/:query/p:page': 'search' | |
}, | |
help: function(){ | |
this.send('some help'); | |
}, | |
search: function(query, page){ | |
this.send('search "' + query + '", page ' + (page || 1)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is really cool.