Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Last active December 26, 2015 14:29
Show Gist options
  • Save mattmccray/7165970 to your computer and use it in GitHub Desktop.
Save mattmccray/7165970 to your computer and use it in GitHub Desktop.
Simple Backbone/Exoskeleton Router for use with React (http://facebook.github.io/react/)
var _missing= function(data){ return React.DOM.pre(null, "Route not found: "+ data.route) },
_router= null,
_started= false,
_nextId= 1;
function handleRouteChange(container, component) {
var routeParams= Array.prototype.slice.call( arguments, 1 )
React.renderComponent(
component({ routeParams:routeParams }, null),
container
)
}
module.exports= {
set404: function(component) {
if(_started) throw "You must set the 404 component before router#start is called!";
if(typeof component != 'function') throw "You must supply a React component to router#set404!";
_missing= component;
},
start: function (container, routes, pushState) {
if(!_router) {
_router= new Backbone.Router();
_router.route('*unknown', '404', function(params) {
React.renderComponent( _missing({ route:params }, null), container );
})
}
for(var route in routes) {
if(! routes.hasOwnProperty(route) ) continue;
var component= routes[route],
name= "route"+ _nextId++;
_router.route(route, name, handleRouteChange.bind(this, container, component));
}
if(!_started) {
pushState= !!pushState;
Backbone.history.start({ pushState:pushState });
_started= true;
}
}
}
var Home= require('ui/page/home'),
Missing= require('ui/page/missing'),
Router= require('core/router')
// Home & Missing are React Components
Router.set404(Missing)
Router.start(document.body, {
'': Home
})
@mattmccray
Copy link
Author

This is based on code from Pete Hunt's ReactHack core: https://github.com/petehunt/reacthack-core/blob/master/lib/ReactHack.js

A notable change in my version, I reuse a single Router. I'm not saying this is better, just cleaner looking. :-)

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