emit-and-callback

Extend (prototype) events.EventEmitter with an emitAndCallback function.

npm install emit-and-callback
1 downloads in the last week
4 downloads in the last month

emit-and-callback

Extend (prototype) events.EventEmitter with an emitAndCallback function.

When you want to support both events and callbacks

If you also keep writing code like this:

this.emit('some event', arg1, arg2);
if(callback !== undefined) {
    callback(arg1, arg2);
}

Then this module is for you!

Find a real working example in the example.js file.

Wherever you normally do something like this:

var util = require('util');
var events = require('events');

var MyClass = function() {
    events.EventEmitter.call(this);
};
util.inherits(MyClass, events.EventEmitter);

MyClass.prototype.emittingFunction = function(callback) {
    this.emit('some event', arg1, arg2);
    if(callback !== undefined) {
        callback(arg1, arg2);
    }
}; 

You can now do this instead:

var util = require('util');
var events = require('events');
require('emit-and-callback');

var MyClass = function() {
    events.EventEmitter.call(this);
};
util.inherits(MyClass, events.EventEmitter);

MyClass.prototype.emittingFunction = function(callback) {
    this.emitAndCallback('some event', arg1, arg2, callback);
}; 

The module will assume that the last argument is a callback function.

The last argument will ALWAYS be removed, but will only be called, if it is actually a function.

This also ensures, you can replace the callback with null, false or anything like that, for convenience and testing.

This is an early BETA version

As soon as the module has shown it's worth and stability on a live system, it will be marked as version >= 1.0.0.

Until then: Feel free to play around with it, learn from it.

To install

npm install emit-and-callback
npm loves you