Skip to content

Instantly share code, notes, and snippets.

@aurri
Last active August 29, 2015 14:03
Show Gist options
  • Save aurri/f6f245c43e66afff3c69 to your computer and use it in GitHub Desktop.
Save aurri/f6f245c43e66afff3c69 to your computer and use it in GitHub Desktop.
Routing with Riot.js
/////////////////////////////////////////////////
//// 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