1 | /*
|
2 | Copyright 2015, 2016 OpenMarket Ltd
|
3 | Copyright 2017 Vector Creations Ltd
|
4 | Copyright 2017 New Vector Ltd
|
5 |
|
6 | Licensed under the Apache License, Version 2.0 (the "License");
|
7 | you may not use this file except in compliance with the License.
|
8 | You may obtain a copy of the License at
|
9 |
|
10 | http://www.apache.org/licenses/LICENSE-2.0
|
11 |
|
12 | Unless required by applicable law or agreed to in writing, software
|
13 | distributed under the License is distributed on an "AS IS" BASIS,
|
14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 | See the License for the specific language governing permissions and
|
16 | limitations under the License.
|
17 | */
|
18 |
|
19 | /**
|
20 | * @module
|
21 | */
|
22 |
|
23 | export class ReEmitter {
|
24 | constructor(target) {
|
25 | this.target = target;
|
26 |
|
27 | // We keep one bound event handler for each event name so we know
|
28 | // what event is arriving
|
29 | this.boundHandlers = {};
|
30 | }
|
31 |
|
32 | _handleEvent(eventName, ...args) {
|
33 | this.target.emit(eventName, ...args);
|
34 | }
|
35 |
|
36 | reEmit(source, eventNames) {
|
37 | // We include the source as the last argument for event handlers which may need it,
|
38 | // such as read receipt listeners on the client class which won't have the context
|
39 | // of the room.
|
40 | const forSource = (handler, ...args) => {
|
41 | handler(...args, source);
|
42 | };
|
43 | for (const eventName of eventNames) {
|
44 | if (this.boundHandlers[eventName] === undefined) {
|
45 | this.boundHandlers[eventName] = this._handleEvent.bind(this, eventName);
|
46 | }
|
47 |
|
48 | const boundHandler = forSource.bind(this, this.boundHandlers[eventName]);
|
49 | source.on(eventName, boundHandler);
|
50 | }
|
51 | }
|
52 | }
|