Last active
August 29, 2015 14:03
-
-
Save aurri/f6f245c43e66afff3c69 to your computer and use it in GitHub Desktop.
Routing with Riot.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///////////////////////////////////////////////// | |
//// The app core | |
// A simple app that inherits from Riot | |
var app = Object.create(riot) | |
// Map urls to app.routes[method](args..) | |
app.route(function(path){ | |
// Split path to an array of params | |
// e.g. '#/hello/big/world' => ['hello', 'big', 'world'] | |
var args = path.split('/').slice(1) | |
// Call the matching method | |
// e.g. ['hello', 'big', 'world'] => app.routes.hello('big', 'world') | |
var method = app.routes[args.shift()||'home'] | |
var handled = method && method.apply(app, args) !== false | |
// If no route found, or handler returned false, redirect home | |
if(!handled) app.route('/') | |
}) | |
///////////////////////////////////////////////// | |
//// The routes (just simple methods) | |
app.routes = {} | |
app.routes.hello = function(size, thing){ | |
// If no "thing", redirect to default | |
if(!thing) return app.route('/hello/'+size+'/world') | |
// If no "size", cancel the route (redirects home) | |
if(!size) return false | |
// If everything's ok, do your thing | |
alert('greetings from the '+size+' '+thing) | |
} | |
app.routes.home = function(){ | |
alert('welcome home') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment