/
index.js
61 lines (48 loc) · 1.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var EventEmitter = require('events').EventEmitter;
var privateErrorEventName = '__domainError';
// Monkey patch the EventEmitter emit function to emit an additional
// '__domainError' event for internal use when an error occurs.
var originalEmitFunction = EventEmitter.prototype.emit;
EventEmitter.prototype.emit = function (eventName) {
if (eventName == 'error') {
originalEmitFunction.call(this, privateErrorEventName, arguments[1]);
}
return originalEmitFunction.apply(this, arguments);
};
var SCDomain = function () {
var self = this;
EventEmitter.call(this);
this.members = [];
this._errorHandler = function errorHandler(err) {
self.emit('error', err);
};
this.run = function (callback) {
var that = this;
var args = arguments;
(new Promise(function (resolve, reject) {
var functionArgs = Array.prototype.slice.call(args, 1);
callback.apply(that, functionArgs);
})).catch(self._errorHandler);
};
};
SCDomain.prototype = Object.create(EventEmitter.prototype);
SCDomain.prototype.bind = function (callback) {
var self = this;
return function () {
self.run.apply(this, [callback].concat(Array.prototype.slice.call(arguments, 0)));
};
};
SCDomain.prototype.add = function (ee) {
this.members.push(ee);
ee.on(privateErrorEventName, this._errorHandler);
};
SCDomain.prototype.remove = function (ee) {
var index = this.members.indexOf(ee);
if (index !== -1) {
ee.removeListener(privateErrorEventName, this._errorHandler);
this.members.splice(index, 1);
}
};
module.exports.create = function () {
return new SCDomain();
};