Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Last active April 18, 2022 15:23
Show Gist options
  • Save yetimdasturchi/3bdf955808bd3953c5ef45fedf94bf78 to your computer and use it in GitHub Desktop.
Save yetimdasturchi/3bdf955808bd3953c5ef45fedf94bf78 to your computer and use it in GitHub Desktop.
let Router = {
routes: {
"/": "index",
"/sayhello/:name": "sayhello"
},
init: function() {
this._routes = [];
for (let route in this.routes) {
let method = this.routes[route];
this._routes.push({
pattern: new RegExp('^' + route.replace(/:\w+/g, '(\\w+)') + '$'),
callback: this[method]
});
}
},
dispatch: function(path) {
var i = this._routes.length;
while (i--) {
var args = path.match(this._routes[i].pattern);
if (args) {
this._routes[i].callback.apply(this, args.slice(1));
}
}
},
index: function() {
console.log('Index route');
},
sayhello: function(name) {
console.log(`Hello ${name}`);
}
}
Router.init();
Router.dispatch('/');
Router.dispatch('/sayhello/Bunny');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment