-
Notifications
You must be signed in to change notification settings - Fork 6
/
BaseDelegate.js
76 lines (61 loc) · 1.77 KB
/
BaseDelegate.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
module.exports = function (console) {
class BaseDelegate {
constructor() {
this.consoleDelegate = this.consoleDelegate.bind(this);
this.recorderDelegate = this.recorderDelegate.bind(this);
this.use = this.use.bind(this);
}
supportsMethods(_methods) {
this._methods = _methods;
for (let i = 0; i < this._methods.length; i++) {
const methodName = this._methods[i];
((methodNameIn) => {
this[methodNameIn] = (...args) => {
this.callDelegate(methodNameIn, args);
};
})(methodName);
}
this.useConsole();
}
callDelegate(methodName, args) {
const items = this.delegates || [];
items.forEach((delegate) => {
if (typeof delegate[methodName] === 'function') {
delegate[methodName].apply(delegate, args);
} else if (typeof delegate === 'function') {
delegate.call(this, methodName, args);
}
});
}
useNoop() {
this.delegates = [];
}
useConsole() {
this.delegates = [this.consoleDelegate];
}
consoleDelegate(methodName, args) {
const prefix = this.getLabel(methodName);
// eslint-disable-next-line no-console
return console.log.apply(console, [prefix].concat(args));
}
getLabel(methodName) {
return `${this.constructor.name}#${methodName}: `;
}
useRecorder() {
this.delegates = [this.recorderDelegate];
}
recorderDelegate(methodName, args) {
if (!this.recorded) {
this.recorded = {};
}
if (!this.recorded[methodName]) {
this.recorded[methodName] = [];
}
this.recorded[methodName].push(args);
}
use(delegate) {
this.delegates = [delegate];
}
}
return BaseDelegate;
};