super-event-emitter (npm)
Super small (2KB) and simple interpretation of popular event management / aggregation.
I was created a blog post (in polish) about this tool: http://piecioshka.pl/blog/2016/01/29/super-event-emitter.html
$ npm install super-event-emitter
$ typings install github:piecioshka/super-event-emitter/typings.json -GD
var foo = EventEmitter.mixin({});
foo.on('test', function () {
console.log('triggered!');
}, this);
foo.emit('test');
var bar = {}; // Or any other object.
EventEmitter.mixin(bar);
bar.on('test', function () {
console.log('triggered!');
}, this);
bar.emit('test');
// File: test.js
class Person {
constructor() {
EventEmitter.mixin(this);
}
say(message) {
this.emit('say', message);
}
}
// In some cases we have an error:
// SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
// so use `var` statement.
var p1 = new Person();
p1.on('say', function (message) {
console.log(message);
});
p1.say('cookie');
Try to test this by: node --harmony test.js
name
- a string value representing the name of eventfn
- action which will be called when event will be triggeredctx
- object will be context of triggered action
Example:
instance.on('foo', function (payload) {
console.log(payload, this);
}, instance);
Special behaviour:
- when
name
=all
(or*
) register handler will be fired on any event
instance.on('all', function (name, payload) {
// will be fired, when emit any of event type
// - name - event name, in this example will be equal: "something"
// - payload - data which are sended, in this example will be equal: { foo: 1 }
});
instance.emit('something', { foo: 1 });
The same as on
but, after triggered event, destroy all listeners
Example:
instance.once('foo', function (payload) {
console.log(payload, this);
}, instance);
name
- a string value representing the name of eventfn
- action which will be removed from listeners
Example:
instance.off('foo', fooHandler);
name
- a string value representing the name of eventparams
- will be passed as first argument in called actions
Example:
instance.emit('foo', { name: 'bar' });
For compatibility with any other APIs I was added some aliases:
on
=>addEventListener
,addListener
,bind
off
=>removeEventListener
,removeListener
,unbind
emit
=>dispatchEventListener
,dispatchListener
,trigger
How to run unit test (written in Jasmine):
$ npm test
Use Istanbul to get code coverage ratio.
$ npm run coverage
The MIT License @ 2016