Last active
December 26, 2015 14:29
-
-
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/)
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
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; | |
} | |
} | |
} |
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
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 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. :-)