-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path6-js-way.js
More file actions
49 lines (38 loc) · 1.04 KB
/
6-js-way.js
File metadata and controls
49 lines (38 loc) · 1.04 KB
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
'use strict';
const EventEmitter = require('node:events');
class Editor extends EventEmitter {
constructor() {
super();
this.document = [];
this.on('edit', ({ name, edit }) => {
this.document.push(edit);
const content = this.getContent();
this.emit('content', { name, content });
});
}
getContent() {
return this.document.join('');
}
}
class User {
constructor(name, editor) {
this.name = name;
this.editor = editor;
editor.on('content', ({ name, content }) => {
if (name === this.name) return;
console.log(`${this.name} sees updated document: "${content}"`);
});
}
makeEdit(edit) {
console.log(`${this.name} edits: "${edit}"`);
this.editor.emit('edit', { name: this.name, edit });
}
}
// Usage
const editor = new Editor();
const user1 = new User('Marcus', editor);
const user2 = new User('Lucius', editor);
console.log('Initial Document:', editor.getContent());
user1.makeEdit('Hello ');
user2.makeEdit('World!');
console.log('Final Document:', editor.getContent());