-
Notifications
You must be signed in to change notification settings - Fork 81
/
Messenger.js
307 lines (274 loc) · 8.16 KB
/
Messenger.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
/* eslint-disable no-underscore-dangle */
import Utils from './Utils';
/**
* Class that can execute functions when local messages are received. Local messages
* are prefixed with the instance's id.
*
* @alias core/Messenger
*
* @property {core/Messenger} GlobalMessenger - A messenger that can be used for
* global messaging. When using static listen and emit methods they are executed
* on this messenger.
* @property {Object} EVENTS - Built-in events that the Messenger emits.
*/
class Messenger {
/**
* @constructor
*
* @param {any=} id - Id for the object. If none is provided a new id will
* be created. Id should be able to be represented as a string.
*/
constructor(id) {
this._id = id !== undefined ? id : Utils.createId();
this._dispatcher = window;
this._callbacks = {};
this._eventListeners = {};
}
/**
* Gets the string id of the object.
*
* @readonly
* @type {string}
*/
get id() {
return this._id;
}
/**
* Prefix a message with the instance id.
*
* @private
*
* @param {string} message
*
* @returns {string}
*/
_createLocalMessage(message) {
return `${this.id}.${message}`;
}
/**
* Return a function that will call a callback function and supply the event's
* detail property as an argument.
*
* @private
*
* @param {Function} callback
*
* @returns {Function}
*/
_createListener(callback) {
return e => {
let value;
if (e.detail !== null) {
value = e.detail;
}
callback(value);
};
}
/**
* Create an event object and send it to listeners.
*
* @private
*
* @param {string} message - Event type name.
* @param {any=} value - Value to send to listeners.
*
* @returns {CustomEvent}
*/
_createEvent(message, value) {
return new CustomEvent(message, {detail: value});
}
/**
* Register an event.
*
* @private
*
* @param {string} message - Event type name.
* @param {Function} listener - A listener function generated using _createListener.
*/
_addListener(message, listener) {
this._dispatcher.addEventListener(
this._createLocalMessage(message),
listener
);
}
/**
* Unregister an event.
*
* @private
*
* @param {string} message - Event type name.
* @param {Function} listener - A listener function generated using _createListener.
*/
_removeListener(message, listener) {
this._dispatcher.removeEventListener(
this._createLocalMessage(message),
listener
);
}
/**
* Execute a function when a message is received for this object.
*
* @param {string} message - The message to listen for.
* @param {Function} callback - Function to execute once the message is received.
*/
listenTo(message, callback) {
if (typeof callback !== 'function') {
throw new Error(
`Cannot add listener for ${message} on ${this.id}. Callback must be a function.`
);
}
if (this._callbacks[message] === undefined) {
this._callbacks[message] = [];
this._eventListeners[message] = [];
}
const listener = this._createListener(callback);
this._callbacks[message].push(callback);
this._eventListeners[message].push(listener);
this._addListener(message, listener);
}
/**
* Prevent a function from being executed when a message is received for this
* object.
*
* @param {string} message - The message to stop listening for.
* @param {Function=} callback - Optional callback to remove. If none is defined,
* remove all callbacks for the message.
*/
stopListening(message, callback) {
if (this._callbacks[message] === undefined) {
return;
} else if (callback === undefined) {
// If no callback was defined, call stopListening on all callbacks for the message
for (let i = this._callbacks[message].length - 1; i > -1; i--) {
this.stopListening(message, this._callbacks[message][i]);
}
return;
}
// If a callback was defined, make sure it's a listener
const index = this._callbacks[message].indexOf(callback);
if (index === -1) {
return;
}
const listener = this._eventListeners[message][index];
this._removeListener(message, listener);
this._callbacks[message].splice(index, 1);
this._eventListeners[message].splice(index, 1);
if (this._callbacks[message].length === 0) {
delete this._callbacks[message];
delete this._eventListeners[message];
}
}
/**
* De-register callback(s) from being executed when messages matching the given
* regular expression are received.
*
* @param {Regexp} regexp - regexp - The regular expression to filter messages with.
* @param {Function=} callback - Optional callback to remove. If none is defined,
* remove all callbacks for messages matching the regular expression.
*/
stopListeningByRegexp(regexp, callback) {
const messages = Object.keys(this._callbacks).filter(message => regexp.test(message));
messages.forEach(message => {
this.stopListening(message, callback);
});
}
/**
* Prevent any functions from being executed when any message is received for
* this object.
*/
stopListeningToAll() {
const messages = Object.keys(this._callbacks);
for (let i = messages.length - 1; i > -1; i--) {
this.stopListening(messages[i]);
}
}
/**
* Send a message, causing listener functions for the message on this object
* to be executed.
*
* @param {string} message - The message to emit.
* @param {any=} value - Optional argument to pass to listener callbacks.
*/
emit(message, value) {
if (this._callbacks[message] === undefined) {
return;
}
message = this._createLocalMessage(message);
const event = this._createEvent(message, value);
this._dispatcher.dispatchEvent(event);
}
/**
* Execute a function when a message is received for the global Messenger instance.
*
* @static
*
* @param {string} message - The message to listen for.
* @param {Function} callback - Function to execute once the message is received.
*/
static listenTo(message, callback, messenger) {
this.GlobalMessenger.listenTo(message, callback, messenger);
}
/**
* Prevent a function from being executed when a message is received for the
* global Messenger instance.
*
* @static
*
* @param {string} message - The message to stop listening for.
* @param {Function=} callback - Optional callback to remove. If none is defined,
* remove all callbacks for the message.
*/
static stopListening(message, callback) {
this.GlobalMessenger.stopListening(message, callback);
}
/**
* De-register callback(s) from being executed on the global messengerr instance
* when messages matching the given regular expression are received.
*
* @param {Regexp} regexp - regexp - The regular expression to filter messages with.
* @param {Function=} callback - Optional callback to remove. If none is defined,
* remove all callbacks for messages matching the regular expression.
*/
static stopListeningByRegexp(regexp, callback) {
const messages = Object.keys(this.GlobalMessenger._callbacks).filter(
message => regexp.test(message)
);
messages.forEach(message => {
this.stopListening(message, callback);
});
}
/**
* Prevent any functions from being executed when any message is received for
* the global Messenger instance.
*
* @static
*/
static stopListeningToAll() {
this.GlobalMessenger.stopListeningToAll();
}
/**
* Send a message, causing listener functions for the message on the global Messenger
* instance to be executed.
*
* @static
*
* @param {string} message - The message to emit.
* @param {any=} value - Optional argument to pass to listener callbacks.
*/
static emit(message, value) {
this.GlobalMessenger.emit(message, value);
}
}
Object.defineProperties(Messenger, {
GlobalMessenger: {
value: new Messenger(),
writable: false,
},
EVENTS: {
value: {},
writable: false,
},
});
export default Messenger;