UNPKG

1.68 kBJavaScriptView Raw
1/*
2Copyright 2015, 2016 OpenMarket Ltd
3Copyright 2017 Vector Creations Ltd
4Copyright 2017 New Vector Ltd
5
6Licensed under the Apache License, Version 2.0 (the "License");
7you may not use this file except in compliance with the License.
8You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12Unless required by applicable law or agreed to in writing, software
13distributed under the License is distributed on an "AS IS" BASIS,
14WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15See the License for the specific language governing permissions and
16limitations under the License.
17*/
18
19/**
20 * @module
21 */
22
23export 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}