Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 85a4d1a

Browse filesBrowse files
committed
Add event adapter example
1 parent 800aa1e commit 85a4d1a
Copy full SHA for 85a4d1a

File tree

Expand file treeCollapse file tree

1 file changed

+35
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+35
-0
lines changed

‎JavaScript/7-events.js

Copy file name to clipboard
+35Lines 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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.