|
| 1 | +/** |
| 2 | + * Copyright (c) 2015-present, Facebook, Inc. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + * |
| 7 | + * @format |
| 8 | + * @flow |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict'; |
| 12 | + |
| 13 | +import EventEmitter from '../emitter/EventEmitter'; |
| 14 | +import EventSubscriptionVendor from '../emitter/EventSubscriptionVendor'; |
| 15 | + |
| 16 | +import type EmitterSubscription from '../emitter/EmitterSubscription'; |
| 17 | + |
| 18 | +const __DEV__ = process.env.NODE_ENV !== 'production'; |
| 19 | + |
| 20 | +function checkNativeEventModule(eventType: ?string) { |
| 21 | + if (eventType) { |
| 22 | + if (eventType === 'appStateDidChange' || eventType === 'memoryWarning') { |
| 23 | + throw new Error( |
| 24 | + '`' + |
| 25 | + eventType + |
| 26 | + '` event should be registered via the AppState module', |
| 27 | + ); |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Deprecated - subclass NativeEventEmitter to create granular event modules instead of |
| 34 | + * adding all event listeners directly to RCTDeviceEventEmitter. |
| 35 | + */ |
| 36 | +class RCTDeviceEventEmitter extends EventEmitter { |
| 37 | + sharedSubscriber: EventSubscriptionVendor; |
| 38 | + |
| 39 | + constructor() { |
| 40 | + const sharedSubscriber = new EventSubscriptionVendor(); |
| 41 | + super(sharedSubscriber); |
| 42 | + this.sharedSubscriber = sharedSubscriber; |
| 43 | + } |
| 44 | + |
| 45 | + addListener( |
| 46 | + eventType: string, |
| 47 | + listener: Function, |
| 48 | + context: ?Object, |
| 49 | + ): EmitterSubscription { |
| 50 | + if (__DEV__) { |
| 51 | + checkNativeEventModule(eventType); |
| 52 | + } |
| 53 | + return super.addListener(eventType, listener, context); |
| 54 | + } |
| 55 | + |
| 56 | + removeAllListeners(eventType: ?string) { |
| 57 | + if (__DEV__) { |
| 58 | + checkNativeEventModule(eventType); |
| 59 | + } |
| 60 | + super.removeAllListeners(eventType); |
| 61 | + } |
| 62 | + |
| 63 | + removeSubscription(subscription: EmitterSubscription) { |
| 64 | + if (subscription.emitter !== this) { |
| 65 | + subscription.emitter.removeSubscription(subscription); |
| 66 | + } else { |
| 67 | + super.removeSubscription(subscription); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +export default new RCTDeviceEventEmitter(); |
0 commit comments