Skip to content

Instantly share code, notes, and snippets.

@boazsender
Created August 30, 2012 14:46
Show Gist options
  • Save boazsender/3529949 to your computer and use it in GitHub Desktop.
Save boazsender/3529949 to your computer and use it in GitHub Desktop.
Sample Backbone.Router use case for backbone.routefilter (https://github.com/boazsender/backbone.routefilter)
/*
* This code does not actually work, it is for demonstration purposes
* of a router using https://github.com/boazsender/backbone.routefilter
*/
// Imagine this came from the server into a big app wide state object
// (likely a Backbone.Model if we were actually doing this for real).
var data = {
// Here are my app's pages (it's content heavy app)
"pages": [{
"name": "page1",
"id": 1,
"layout": "list",
"content": { ... }
},
{
"name": "page2",
"id": 12,
"layout": "list",
"content": { ... }
}
],
// Here is my bottom navigation
"navigationbar": [
{
"text": "page1",
"icon": "../img/coolicon1.png",
"route": "page1"
},
{
"text": "page2",
"icon": "../img/coolicon1.png",
"route": "page2"
},
{
"text": "page3",
"icon": "../img/coolicon3.png",
"route": "page3"
}
]
}
// Make a new collection and add the pages to it, so we can
// use .where to check an arbitrary route against a node's name
var pages = new Backbone.Collection();
pages.add( data.pages );
// Setup our router just like normal
var Router = Backbone.Router.extend({
// set our route table with only one wild card route
routes: {
"": "index",
"*path": "page"
},
// Use the backbone.routefilter before filter
before: function( route ){
// If the route is falsey, then we're at "/", pass
if(!route){
return;
}
// If the route arg does not exist as a named page in our
// app data object then we have a problem.
// decodeURI in case there is a space in the page/route name
if( pages.where({ name: decodeURI(route) }).length ){
// Render a content not found page using a view we made somewhere else.
var view = new NotFoundView({ model: page });
view.render();
// return false to prevent the page callback from running.
return false;
}
},
index: function( route ){
// Call some view we made somewhere else and render it
var view = new IndexView();
view.render();
}
// This callback will run for every page. It wont run if before
// returns false.
page: function( route ){
// Get the page from the route
// decodeURI in case there is a space in the page/route name
var page = pages.where({ name: decodeURI(route) })[0];
// Call some view we made somewhere else and render it
var view = new PageView({ model: page });
view.render();
}
});
return Router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment