Skip to content

Instantly share code, notes, and snippets.

@gabriel-dehan
Created April 20, 2012 09:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabriel-dehan/2427251 to your computer and use it in GitHub Desktop.
Save gabriel-dehan/2427251 to your computer and use it in GitHub Desktop.
How to implement a router in Meteor-0.3.2
/* It calls the content helper, and then load the Template matching the route :
for exemple, /user/list will load the template "user_list"
It's not optimum but it works
*/
<template name="container">
<div class="container">
{{#content}}
{{/content}}
</div>
</template>
if ( Meteor.is_client ) {
ClientRouter = Backbone.Router.extend({
routes: {
":route/" : "get_route",
":route/:action/" : "get_route"
},
/* Generic routes */
get_route: function( route, action ) {
var args, query;
if ( action ) {
args = action.split('?');
query = args[1];
action = args[0];
}
Meteor.request.setController(route);
Meteor.request.setAction(action);
Meteor.request.setQuery(query);
},
/* Every time a route is called we set it in the Session */
initialize: function() {
this.bind("all", function() {
Session.set('route', Backbone.history.fragment);
});
}
});
var Router = new ClientRouter;
Backbone.history.start({pushState: true});
// Here I'm using the Base library for class convenience (I don't really like the way Javascript handles OO) : @see : http://dean.edwards.name/weblog/2006/03/base/
var Request = Base.extend({
constructor: function() {
},
setController: function( controller ) {
this.controller = controller;
},
setAction: function( action ) {
this.action = action;
},
setQuery: function( query ) {
if (query) {
var query_object = {};
query.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { query_object[$1] = $3; }
);
}
this.query = query_object;
}
});
Meteor.request = new Request;
/**
* Loads the template according to the route
*/
Handlebars.registerHelper('content', function(){
/* This does nothing but triggers the Meteor.ui.chunk HTML automatic update on route change */
Session.get('route');
/* If the Route changes (mostly via Router.navigate('new/route', {trigger:true}), Meteor.ui.chunk allows our content to be re-rendered */
return Meteor.ui.chunk(Template[Meteor.get_template()]);
});
Meteor.get_template = function() {
Meteor.view = Meteor.request.controller;
Meteor.view += Meteor.request.action ? '_' + Meteor.request.action : '' ;
// Error handling
return Meteor.view;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment