Skip to content

Commit 85a4d1a

Browse files
committed
Add event adapter example
1 parent 800aa1e commit 85a4d1a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

JavaScript/7-events.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
3+
const { EventEmitter } = require('events');
4+
5+
class AdaptiveEmitter extends EventEmitter {
6+
constructor() {
7+
super();
8+
this.transformations = {};
9+
}
10+
transform(from, to, fn) {
11+
this.transformations[from] = { to, fn };
12+
}
13+
emit(name, ...args) {
14+
const transform = this.transformations[name];
15+
if (transform) {
16+
super.emit(transform.to, ...transform.fn(...args));
17+
}
18+
super.emit(name, ...args);
19+
}
20+
}
21+
22+
// Usage
23+
24+
const ae = new AdaptiveEmitter();
25+
ae.transform('timer', 'timeout', date => [date.toLocaleString()]);
26+
27+
ae.on('timeout', date => {
28+
console.dir({ date });
29+
});
30+
31+
setTimeout(() => {
32+
const date = new Date();
33+
console.log('new Date():', date);
34+
ae.emit('timer', date);
35+
}, 1000);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy