embark-area-51/lib/core/events.js

70 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-03-31 11:34:43 +00:00
var EventEmitter = require('events');
function warnIfLegacy(eventName) {
2018-05-22 19:00:46 +00:00
const legacyEvents = [];
if (legacyEvents.indexOf(eventName) >= 0) {
2018-05-08 21:49:46 +00:00
console.info(__("this event is deprecated and will be removed in future versions %s", eventName));
}
}
2017-10-13 09:56:42 +00:00
function log(eventType, eventName) {
if (['end', 'prefinish', 'error', 'new', 'demo', 'block', 'version'].indexOf(eventName) >= 0) {
return;
}
2018-07-26 16:58:25 +00:00
// prevents infinite loop when printing events
if (eventType.indexOf("log") >= 0) {
return;
}
2017-10-13 09:56:42 +00:00
}
2018-06-29 14:29:07 +00:00
EventEmitter.prototype._maxListeners = 350;
const _on = EventEmitter.prototype.on;
const _once = EventEmitter.prototype.once;
const _setHandler = EventEmitter.prototype.setHandler;
EventEmitter.prototype.on = function(requestName, cb) {
2017-10-13 09:56:42 +00:00
log("listening to event: ", requestName);
warnIfLegacy(requestName);
return _on.call(this, requestName, cb);
};
EventEmitter.prototype.once = function(requestName, cb) {
log("listening to event (once): ", requestName);
warnIfLegacy(requestName);
return _once.call(this, requestName, cb);
};
EventEmitter.prototype.setHandler = function(requestName, cb) {
2017-10-13 09:56:42 +00:00
log("setting handler for: ", requestName);
warnIfLegacy(requestName);
return _setHandler.call(this, requestName, cb);
};
EventEmitter.prototype.request = function() {
let requestName = arguments[0];
let other_args = [].slice.call(arguments, 1);
2017-10-13 09:56:42 +00:00
log("requesting: ", requestName);
warnIfLegacy(requestName);
return this.emit('request:' + requestName, ...other_args);
};
EventEmitter.prototype.setCommandHandler = function(requestName, cb) {
2018-05-23 15:16:13 +00:00
log("setting command handler for: " + requestName);
2018-05-16 17:57:27 +00:00
let listener = function(_cb) {
cb.call(this, ...arguments);
2018-05-16 19:18:12 +00:00
};
2018-05-16 17:57:27 +00:00
// unlike events, commands can only have 1 handler
this.removeAllListeners('request:' + requestName);
return this.on('request:' + requestName, listener);
};
EventEmitter.prototype.setCommandHandlerOnce = function(requestName, cb) {
log("setting command handler for: ", requestName);
return this.once('request:' + requestName, function(_cb) {
cb.call(this, ...arguments);
});
};
module.exports = EventEmitter;