oo-router
v0.0.5
Published
Routing
Downloads
2
Readme
router
Installation
npm install oo-router
Usage
Browser
var router = require("oo-router");
var productController = {
view: function(path, id) {},
edit: function(path, id) {}
};
var productRouter = router()
.add(/^\/product\/(\d+)\/view$/, productController.view)
.add(/^\/product\/(\d+)\/edit$/, productController.edit)
.process;
var accountController = {
login: function(path, username) {},
logout: function(path) {},
register: function(path) {}
};
var accountRouter = router()
.add(/^\/account\/login\/(\w+)$/, accountController.login)
.add(/^\/account\/logout$/, accountController.logout)
.add(/^\/account\/register$/, accountController.register)
.process;
var process = router()
.add(/^\/product/, productRouter)
.add(/^\/account/, accountRouter)
.add(/^$/, index)
.process;
window.addEventListener("hashchange", function() {
process(window.location.hash.substring(1));
});
Server
var router = require("oo-router");
var http = require("http");
var apiController = function(path, req, res, controllerId, objectId) {
// path = "api/product/20"
// controlerId = "product"
// objectId = "20"
};
var process = router()
.add(/^\/api\/(\w+)\/(\d+)$/, apiController)
.add(/.*/, staticFileServer)
.process;
http.createServer(function(req, res) {
process(req.url, req, res); // req & res will be passed to the route handler
});
API
router()
Create a new router
router().add(regexp, handler)
Add a new route, returns itself
regexp
Regular Expression to match the routehandler
Function to be called when this route is matched
Handler receives all parameters passed to router().process
as well as regexp matches
router().process(url, [...])
Process an URL
url
URL to be processed[...]
rest parameters will be passed to the matched route handler