AmpersandJS / tools.ampersandjs.com

Hand-picked tools for building ampersand apps. A grab bag of "solved problems" for single page apps.
https://tools.ampersandjs.com
MIT License
11 stars 2 forks source link

ampersand-dependency-mixin #9

Closed wookiehangover closed 10 years ago

wookiehangover commented 10 years ago

https://github.com/wookiehangover/ampersand-dependency-mixin npm install ampersand-dependency-mixin

This is a mixin for managing dependencies that are passed to a constructor as options. It will automatically attach specified keys in the options object, throwing errors if they're not present. This makes it easy to enforce (and test) the required options for a class and provides sensible error messages when they're missing.

I've used similar patterns across a number of Backbone projects over the past few years and I think it fits nicely into the rest of the amper-verse.

Example:

var User = Model.extend(dependencyMixin, {
  dependencies: ['config'],
  initialize: function(options) {
    this.attachDeps(options);
  }
});

new User();
// -> Error: 'Missing required dependencies: `config`'

var user = new User({ config: 'foo' });
user.config
// -> 'foo'

NB: I stayed away from the term "dependency injection" because it's a bit overloaded.

Thanks!

HenrikJoreteg commented 10 years ago

Added, thanks Sam!