0.2.0 • Published 11 years ago

huggybear v0.2.0

Weekly downloads
1
License
-
Repository
github
Last release
11 years ago

Huggy Bear

npm.io

Huggy was so cool he owned an iPad in the 70s!

What it does

HuggyBear does "silent mixin". It creates and stores functionnality for any object without never ever needing to compromise their structure or properties.

An example

Suppose an instance of the People prototype, with 3 methods: walk, sleep, work (very limited, huh?).

Now you want the instances of People to be also instances of EventEmitter, you'll have to add on, off, emit.

And now, you want the instances of People to do PubSub, then you add publish and subscribe.

So what ?

So your handcrafted People prototype, with the pure and beautiful simplicity of its 3 methods, has just lost its essence and is now a kind of a hydra with 8 methods, namely walk, sleep, work, on, off, emit, publish, register.

HuggyBear will keep your models sane and simple.

Some code, please

var huggyBear = require('huggybear');

function People () {
  huggyBear.provide(this, '/path/to/mixins/EventEmitter' /*, mixinArg1, mixinArg2 */);
}

People.prototype = {
  walk: function () {},
  sleep: function () {},
  work: function () {}
}

var ppl = new People();
ppl.on('eventName', function () {}); // throws TypeError, obviously
pplEventEmitter = huggyBear.claim('/path/to/mixins/EventEmitter');
pplEventEmitter.on('eventName', function () {}); //OK

You don't have to use the prototypal inheritance for HuggyBear to work. It's just that I'm kind of old fashioned, in some way.

You don't even have to put it in the constructor, of course. Add functionnality whenever you need to.

Building a mixin

To build a mixin, you must build a CommonJS module which exports MUST be a function. it can take any number of parameters, you will pass them by appending parameters to huggyBear#provide.

In other words, the exports of your module is the generator (aka the factory) of your mixin.

An exemple for a mixin of EventEmitter

var EventEmitter = require('events').EventEmitter;

module.exports = function () {
  return new EventEmitter();
};

For every object that wants this mixin to be provided, an instance of Emitter is created. Each object get its own instance.

Simple.

HuggyBear everywhere

You may want to bring HuggyBear to every object...

var huggyBear = require('huggybear');

Object.prototype.provide = function (/*name, arg1, arg2 */) {
  return huggyBear.provide.apply(undefined, [this].concat(Array.prototype.slice.call(arguments)));
}

Object.prototype.claim = function (/*name*/) {
  return huggyBear.claim.apply(undefined, [this].concat(Array.prototype.slice.call(arguments)));
}

Inception

You can use HuggyBear from HuggyBear to create multiple dependency containers, each being isolated from the other.

Testing

The tests and coverage reports are available in the TESTING file.

License

MIT

0.2.0

11 years ago

0.1.0

11 years ago