@adt/event-emitter
Version:
Simple event emmiter implementation
77 lines (61 loc) • 2.05 kB
JavaScript
;
/**
* Callback
* @class
* @private
* @param {String} evtName Event name
* @param {Function} callback Callback function
* @param {Object} context Callback execution context
* @param {?Object} args Additional arguments
*/
function Callback(evtName, callback, context, args) {
return Object.freeze(Object.create(null, {
evtName: { value: evtName },
callback: { value: callback },
context: { value: context },
args: { value: args }
}));
}
/**
* EventEmitter
*/
function EventEmitter() {
var _this = this;
var callbacks = new Map();
var ret = Object.create(EventEmitter.prototype, {
/**
* Register callback function.<br />
* Event object will be passed to registered callback function as first argument.
* @name EventEmitter#on
* @memberof EventEmitter
* @function
* @param {String} evtName Event name
* @param {Function} cbf Callback function
* @param {Object} [context=EventEmitter] Callback execution context (this)
*/
on: { value: function value(evtName, cbf, context) {
var ctx = context || _this;
var cb = Callback(evtName, cbf, ctx);
if (callbacks.has(evtName)) {
callbacks.get(evtName).push(cb);
} else {
callbacks.set(evtName, [cb]);
}
} },
/**
* Execute callbacks on given event if callbacks exist for this event (emit events).
* @protected
* @param {String} evtName Event name
* @param {Object} evt Associated source event
*/
emit: { value: function value(evtName, evt) {
if (callbacks.has(evtName)) {
callbacks.get(evtName).forEach(function (cb) {
return cb.callback.call(cb.context, evt);
});
}
} }
});
return ret;
}
module.exports = EventEmitter;