Files
react-native/Libraries/Utilities/DevSettings.js
T
Tim Yung d39643b9de RN: Rewrite NativeEventEmitter
Summary:
Rewrites `NativeEventEmitter` to not extend `EventEmitter` and to compose `RCTDeviceEventEmitter` instead of (mis)using its exported `sharedSubscriber` property.

This makes it easier to reason about `NativeEventEmitter`. Also, the extraneous methods on `EventEmitter` are no longer inherited.

Changelog:
[General][Removed] - `NativeEventEmitter` no longer inherits from `EventEmitter`, so it no longer implements `removeListener` and `removeSubscription`. Instead, use the `remove()` method on the subscription object returned by `addListener`.

Reviewed By: rubennorte

Differential Revision: D26163562

fbshipit-source-id: c1aadb99bdefbaa36fece57ce74604e414f94d4d
2021-02-09 21:27:45 -08:00

68 lines
1.9 KiB
JavaScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import NativeDevSettings from '../NativeModules/specs/NativeDevSettings';
import NativeEventEmitter from '../EventEmitter/NativeEventEmitter';
let DevSettings: {
addMenuItem(title: string, handler: () => mixed): void,
reload(reason?: string): void,
onFastRefresh(): void,
} = {
addMenuItem(title: string, handler: () => mixed): void {},
reload(reason?: string): void {},
onFastRefresh(): void {},
};
type DevSettingsEventDefinitions = {
didPressMenuItem: [{title: string}],
};
if (__DEV__) {
const emitter = new NativeEventEmitter<DevSettingsEventDefinitions>(
NativeDevSettings,
);
const subscriptions = new Map();
DevSettings = {
addMenuItem(title: string, handler: () => mixed): void {
// Make sure items are not added multiple times. This can
// happen when hot reloading the module that registers the
// menu items. The title is used as the id which means we
// don't support multiple items with the same name.
let subscription = subscriptions.get(title);
if (subscription != null) {
subscription.remove();
} else {
NativeDevSettings.addMenuItem(title);
}
subscription = emitter.addListener('didPressMenuItem', event => {
if (event.title === title) {
handler();
}
});
subscriptions.set(title, subscription);
},
reload(reason?: string): void {
if (NativeDevSettings.reloadWithReason != null) {
NativeDevSettings.reloadWithReason(reason ?? 'Uncategorized from JS');
} else {
NativeDevSettings.reload();
}
},
onFastRefresh(): void {
NativeDevSettings.onFastRefresh?.();
},
};
}
module.exports = DevSettings;