franciscop / pagex
- четверг, 18 августа 2016 г. в 03:15:33
JavaScript
A simple router for the browser in javascript
A simple front-end routing for your pages. It loads the script only when the DOM is ready. It can handle both Regex and paths
pagex(path, [negate?], callback);
If you have a large javascript codebase, you can split it the following way:
// Logic for all your pages. For example, analytics
analytics();
// Logic specific for your /users page and subpages
pagex('/users', function(){
// ...
});
// Logic specific for your /books page and subpages
pagex('/books', function(){
// ...
});
A simple front-end router based on express.js router, which is based on path-to-regexp:
pagex('/hi', function(){
alert('Hi there!');
});
You can get the url parameters easily:
pagex('/users/:username', function(username){
alert('Hi there ' + username + '!');
});
Make them optional:
// Note: ES6 default parameter shown here
pagex('/users/:username?', function(username = 'everyone'){
alert('Hi there ' + username + '!');
});
Originally the main way of doing this was with pure regex (that's why it's called pagex, from Page + Regex). However, the main way now is with paths that get converted internally to regex. If you want to use regex you can do so:
// Starts by a string
pagex(/^\/user/, function(){
console.log("User section loaded");
});
// When NOT in this page, since negating in regex is complex: stackoverflow.com/a/1240337
pagex(/^\/user/, true, function(){
console.log("User index");
});
// Strict page
pagex(/^\/user$/, function(){
console.log("User index");
});
// Parameters from capturing groups, with required id
pagex(/^\/user\/([A-Za-z0-9]+)/, function(id){
console.log("Hello user " + id + "!");
});
// Parameters from capturing groups, with optional id
pagex(/^\/user\/?([A-Za-z0-9]+)?/, function(id){
console.log("Are you there, user " + id + "?");
});