Skip to content

Instantly share code, notes, and snippets.

@maxpert
Last active August 12, 2020 18:35
Show Gist options
  • Save maxpert/8110903 to your computer and use it in GitHub Desktop.
Save maxpert/8110903 to your computer and use it in GitHub Desktop.

Javascript #router. Features:

  • Just 70 lines of code.
  • Router scope can be bound to any object (default window); just change first parameter
  • Triggers custom DOM (Level 2) events on window.document.
  • IE 9+, FF, and Webkit based browsers [Tested only in Chrome and FF].
window.document.addEventListener("route.changed", function (e) {
console.log(e.data.route, "------", e.data.params);
}, false);
Router.map("/foo", "route.changed");
Router.map("/foo/(bar-map)", "route.changed");
Router.map("/foo/(bar)/name", function (e){
console.log("Direct callback", e);
});
Router.start();
/*
Copyright (c) 2013 Zohaib Sibte Hassan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function($, win) {
var Routes = [];
var doc = win.document;
function fireCustomEvent(name, data) {
var evt = doc.createEvent("HTMLEvents");
evt.initEvent(name, true, true ); // event type,bubbling,cancelable
evt.data = data;
return !doc.dispatchEvent(evt);
}
function hashChange() {
var url = (win.location.hash || "#").slice(1);
$.Router.match(url);
}
$.Router = {
map: function (r, e) {
// Escape anything except () and replace (name) with (.+)
var es_tmp = r.replace(/[-[\]{}*+?.,\\^$|#\s]/g, "\\$&").replace(/\([^\)]+\)/g, "([^/]+)");
var r_exp = new RegExp("^"+es_tmp+"$", "g");
// Save names and routes under with expression and variable names
Routes.push({
exp: r_exp,
names: r_exp.exec(r).slice(1),
event: e
});
},
match: function (r) {
for(var i in Routes) {
var rout = Routes[i];
if (r.match(rout.exp)){
var params = {};
info = rout.exp.exec(r).slice(1);
for(var k in info) {
params[rout.names[k].replace(/[()]/g, "")] = info[k];
}
if(typeof rout.event === 'function') {
rout.event({data: {params: params, route: r}});
}else if( typeof rout.event === 'string') {
fireCustomEvent(rout.event, {params: params, route: r});
}
}
}
},
start: function() {
if (window.addEventListener) {
window.addEventListener("hashchange", hashChange, false);
}
else if (window.attachEvent) {
window.attachEvent("onhashchange", hashChange);
}
hashChange(); // Call first time for loading first URL
},
stop: function() {
if (window.removeEventListener) {
window.removeEventListener("hashchange", hashChange, false);
}
else if (window.attachEvent) {
window.detachEvent("onhashchange", hashChange);
}
}
};
})(window, window);
@fosron
Copy link

fosron commented Jan 30, 2014

info = rout.exp.exec(r).slice(1); Causes error (TypeError: rout.exp.exec(...) is null) on Firefox 26

@fosron
Copy link

fosron commented Jan 30, 2014

A simple fix for this is:

if(rout.exp.test(r)){
info = rout.exp.exec(r).slice(1);
for(var k in info) {
params[rout.names[k].replace(/[()]/g, "")] = info[k];
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment