/**
* router
* @description Run callbacks when a route pattern matches current pathname
*/
(function (window, document, module, undefined) {
var matchRoute = function (route) {
var pathRegEx = '^' + route.path;
if (/\*$/.test(route.path)) {
pathRegEx.slice(0, -1) + '+.';
} else {
if (route.path !== '/') {
pathRegEx += '/?';
}
pathRegEx += '$';
}
return RegExp(pathRegEx, 'gi').test(window.location.pathname);
},
extend = function () {
var extended = {};
for(var key in arguments) {
var argument = arguments[key];
for (var prop in argument) {
if (Object.prototype.hasOwnProperty.call(argument, prop)) {
extended[prop] = argument[prop];
}
}
}
return extended;
},
Router = function () {
this.routes = [];
};
Router.prototype = extend(Router.prototype, {
addRoutes: function (routes) {
this.routes = this.routes.concat(routes);
},
doRoute: function () {
var routes = this.findRoute(this.routes);
if (routes.length) {
routes.forEach(function (route) {
if (route.destroy && route.destroy.length) {
this.callOnRoute(route, 'destroy');
}
if (route.create && route.create.length) {
this.callOnRoute(route, 'create');
}
}, this);
}
},
findRoute: function (routes) {
return routes.filter(matchRoute);
},
callOnRoute: function (modules, type) {
if (type) {
modules = modules[type];
}
modules.forEach(function (method) {
if (method instanceof Function) {
method();
}
});
}
});
if (typeof module === 'object' && module.exports) {
module.exports = Router;
} else {
window.Router = Router;
}
}(window, document, module));
/**
* Example Usage
*
* This is assuming you're using a module/revealing module pattern, etc.
* You can just write functions and list them in the create/destroy array.
*
* var router = new Router();
*
* router.addRoutes([
* {
* path: '/*' // Call on all routes
* create: [app.base.init],
* destroy: [] // Nothing to destroy
* },
* {
* path: '/' // Only call on home page
* create: [app.home.init],
* // Nothing to destroy, so just leave it off
* },
* {
* path: '/about' // Only call on main about page
* create: [app.about.init]
* },
* {
* path: '/about*' // Call on all routes in the about section
* create: [app.aboutSlider.init]
* },
* {
* path: '/about/team' // Only call on "/about/team"
* create: [app.aboutTeam.init]
* }
* ]);
*
* router.doRoute();
*
Call "create" and "destroy" methods based on url. Basically only initialize code specific to a url or group of urls. Works with and without Browserify.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.