0.0.5 • Published 10 years ago
oo-router v0.0.5
router
Installation
npm install oo-routerUsage
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
regexpRegular Expression to match the routehandlerFunction 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
urlURL to be processed[...]rest parameters will be passed to the matched route handler