Skip to content

Instantly share code, notes, and snippets.

@jasoncrawford
Last active November 23, 2018 15:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasoncrawford/10547835 to your computer and use it in GitHub Desktop.
Save jasoncrawford/10547835 to your computer and use it in GitHub Desktop.
Backbone flash mechanism
var Backbone = require('backbone');
// Flash ///////////////////////////////////////////////////////////////////////////////////////////
// The flash is a way for one controller to pass a small amount of information to the next
// controller, through a navigation event.
//
// The flash holds arbitrary parameters, and is cleared by the router after each navigation event.
var flash = exports.flash = {
params: {},
addParams: function (options) {
_.extend(this.params, options);
},
perform: function (object) {
if (_.isEmpty(this.params)) return;
if (object && typeof object.onFlash === 'function') {
object.onFlash(this.params);
}
this.params = {};
},
}
// Router //////////////////////////////////////////////////////////////////////////////////////////
// Router is our custom extension of the Backbone router, with the routes we need for our app.
var Router = exports.Router = Backbone.Router.extend({
routes: {
// Custom for your app
},
// Sets parameters in the flash (see above).
flash: function (params) {
flash.addParams(params);
return this;
},
// Overrides Backbone.Router#navigate to “flash” the new controller after navigation (see above).
navigate: function () {
Backbone.Router.prototype.navigate.apply(this, arguments);
flash.perform(this.root);
return this;
},
// ...
});
// Create a single global router object for views to use
var router = exports.router = new Router();
// At some point in your startup code, you need to set the root view something like this:
//
// router.root = new RootView({el: $('#root')});
// Backbone.history.start({pushState: true});
//
// The RootView needs to handle onFlash, possibly delegating to child views.
var routing = require('./routing')
var Backbone = require('backbone');
var MyView = Backbone.View.extend({
// ...
events: {
'click .foo': function (event) {
// Invoke the flash before navigation like this:
routing.router.flash({foo: 1, bar: 2}).navigate('/path', {trigger: true});
}
},
onFlash: function (params) {
// Handle the flash params here, possibly delegating to child views
},
// ...
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment