Skip to content

Instantly share code, notes, and snippets.

@weotch
Last active March 13, 2016 12:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save weotch/5878445 to your computer and use it in GitHub Desktop.
Save weotch/5878445 to your computer and use it in GitHub Desktop.
Backbone routing example using require.js
// This our standard require js bootstrap file. It assumes you are using the
// require-jquery.js file that require.js provides
// Set the require.js configuration for the application
require.config({
// Base path used to load scripts
baseUrl: 'js/',
// Prevent caching during dev
urlArgs: "bust=" + (new Date()).getTime(),
// Exclude these modules on build
stubModules: ['text'],
// Set common library paths
paths: {
jquery: 'empty:', // jquery is already loaded
underscore: 'libs/underscore',
backbone: 'libs/backbone'
}
});
// Define the application entry point
define('main', function (require) {
// Dependencies
var $ = require('jquery'),
router = require('router'); // This is the router.js file. Note, it gets invoked before DOM is loaded
// Auto go to a project detail page. Trigger = true will tell it to run the callback
// function from the router definition.
router.navigate("project/some-slug", {trigger:true})
});
// Start the application
require(['main']);
define(function(require) {
// Dependencies
var $ = require('jquery'),
Backbone = require('backbone');
// Create router. We're assuming you aren't doing anything nuts, thus a single router
// for the whole site is suffient
var router = Backbone.Router.extend({
// Define routes
routes: {
"": "home",
"projects": "projects",
"project/:slug": "project",
},
// Handle those routes. These callbacks get called when navigate is called with
// trigger = true
project: function(slug) { },
projects: function() {},
home: function() {} // The home page
});
// Listen for history changes
Backbone.history.start({
pushState: true,
silent: true // This assumes that the server is handling the initial route and rendering your deep link
});
// Return the router for triggering links
return router;
});
@capir
Copy link

capir commented Nov 14, 2013

Hey weotch,

I think you should put

var router = new Router();

before calling navigate.

Nice gist btw. Good luck!

@awakentwice
Copy link

Thanks for the gist!

@rundef
Copy link

rundef commented Dec 23, 2015

Hi,
in router.js, I had to change return router; to return new router(); to make it work

Copy link

ghost commented Mar 13, 2016

BTW: is the ':emtpy' a valid configuration? I didn't cache it on docs (requirejs).
Great idea though.

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