forked from tzeikob/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauditor.js
70 lines (56 loc) · 1.35 KB
/
auditor.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
var myNS = myNS || Object.create(null);
myNS.User = function User(data) {
this.id = data.id;
this.name = data.name;
this.notifications = [];
this.observers = [];
};
myNS.User.prototype.notify = function notify(message) {
this.notifications.push(message);
this.ping({
action: 'receive',
subject: this.name,
payload: message
});
};
myNS.User.prototype.send = function send(message, user) {
this.ping({
action: 'send',
subject: this.name,
payload: message
});
user.notify(message);
};
myNS.User.prototype.attach = function attach(observer) {
this.observers.push(observer);
};
myNS.User.prototype.ping = function ping(context) {
this.observers.forEach(o => {
o.notify(context);
});
};
myNS.Auditor = function Auditor(cb) {
this.cb = cb;
};
myNS.Auditor.prototype.notify = function notify(context) {
this.cb(context);
};
let auditor = new myNS.Auditor((context) => {
if (context.action === 'send') {
console.log(`User ${context.subject} send the message: ${context.payload}`);
} else if (context.action === 'receive') {
console.log(`User ${context.subject} receive the message: ${context.payload}`);
}
});
let u1 = new myNS.User({
id: '1',
name: 'Bob'
});
let u2 = new myNS.User({
id: '2',
name: 'Alice'
});
u1.attach(auditor);
u2.attach(auditor);
u1.send('Hi', u2);
u2.send('Hello', u1);