Skip to content

Instantly share code, notes, and snippets.

@timruffles
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timruffles/9623942 to your computer and use it in GitHub Desktop.
Save timruffles/9623942 to your computer and use it in GitHub Desktop.
getting globalish things down (event source, session) into components - without breaking unit testing
// overall idea is to use prototype props
// to give access to shared instances of
// 'globalish' stuff like session/router,
// but without resorting to globals. If we
// used straight globals, we couldn't have
// half the app using a different instance
// which might be necessary in future and is
// certaintly necess in testing
// so from use-case to implementation:
function bootApp() {
var router = new AppRouter();
var session = new Session();
// plug in our top level deps
View.setDependencies({router: router, session: session});
}
function testSomeView() {
var instance = new View({
session: {
// mocking/stubbing still very
// easy and predictable, rather
// than globals which can't be per-instance
login: function() {}
}
})
}
// here's how it works
var View = Backbone.View.extend({
constructor: function(opts) {
// allows for per-instance session/router
_.extend(this,_.pick(opts,"session","router"));
return Backbone.View.call(this,opts); // might be more fiddle, but you get the idea: `super()`
},
createChild: function(constructor,opts) {
// cuts down on the boiler-plate required for passing down instance specific
// session/router etc
return new constructor(_.defaults(opts,{
session: this.session,
router: this.router
}))
}
},{
setDependencies: function(opts) {
// used to set app level instances
_.extend(View.prototype,opts);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment