UNPKG

2.33 kBJavaScriptView Raw
1/**
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. 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,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18*/
19
20var EventEmitter = require('events').EventEmitter;
21
22var INSTANCE = new EventEmitter();
23INSTANCE.setMaxListeners(20);
24var EVENTS_RECEIVER;
25
26module.exports = INSTANCE;
27
28/**
29 * Sets up current instance to forward emitted events to another EventEmitter
30 * instance.
31 *
32 * @param {EventEmitter} [eventEmitter] The emitter instance to forward
33 * events to. Falsy value, when passed, disables forwarding.
34 */
35module.exports.forwardEventsTo = function (eventEmitter) {
36
37 // If no argument is specified disable events forwarding
38 if (!eventEmitter) {
39 EVENTS_RECEIVER = undefined;
40 return;
41 }
42
43 if (!(eventEmitter instanceof EventEmitter)) { throw new Error('Cordova events can be redirected to another EventEmitter instance only'); }
44
45 // CB-10940 Skipping forwarding to self to avoid infinite recursion.
46 // This is the case when the modules are npm-linked.
47 if (this !== eventEmitter) {
48 EVENTS_RECEIVER = eventEmitter;
49 } else {
50 // Reset forwarding if we are subscribing to self
51 EVENTS_RECEIVER = undefined;
52 }
53};
54
55var emit = INSTANCE.emit;
56
57/**
58 * This method replaces original 'emit' method to allow events forwarding.
59 *
60 * @return {eventEmitter} Current instance to allow calls chaining, as
61 * original 'emit' does
62 */
63module.exports.emit = function () {
64
65 var args = Array.prototype.slice.call(arguments);
66
67 if (EVENTS_RECEIVER) {
68 EVENTS_RECEIVER.emit.apply(EVENTS_RECEIVER, args);
69 }
70
71 return emit.apply(this, args);
72};