### Events Keep in mind: - Events share namespace (so come up with an app-wide naming convention) #### React ```js import { NativeEventEmitter, NativeModules } from 'react-native' const videoPlayer = NativeModules.VideoPlayer const videoPlayerEmitter = new NativeEventEmitter(VideoPlayer) const subscription = videoPlayerEmitter.addListener('video-progress', (data) => console.log(data.progress)) // Don't forget to unsubscribe, typically in `componentWillUnmount` subscription.remove() ``` #### iOS [docs](https://facebook.github.io/react-native/docs/native-modules-ios.html#sending-events-to-javascript) > __Important Note:__ > Don't send events if there are no listeners attached. You will get a warning about spending > unneccessary resources. Override `-startObserving` and `-stopObserving` like in the example below: ```obj-c // VideoPlayer.h #import #import @interface CalendarManager : RCTEventEmitter @end // VideoPlayer.m #import "VideoPlayer.h" @implementation VideoPlayer { BOOL _hasListeners; } RCT_EXPORT_MODULE(); - (NSArray *)supportedEvents { return @[@"video-progress"]; } // Will be called when this module's first listener is added. - (void)startObserving { _hasListeners = YES; } // Will be called when this module's last listener is removed, or on dealloc. - (void)stopObserving { _hasListeners = NO; } - (void)onVideoProgress { CGFloat progress = ...; if (_hasListeners) { [self sendEventWithName:@"video-progress" body:@{ @"progress": @(progress) }]; } } @end ``` #### Android [docs](https://facebook.github.io/react-native/docs/native-modules-android.html#sending-events-to-javascript) [example](http://stackoverflow.com/a/40232448/598993) ```java private void onVideoProgress() { WriteableMap params = Arguments.createMap(); ... reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("video-progress", params); } ``` [__Go to Top__](https://gist.github.com/chourobin/f83f3b3a6fd2053fad29fff69524f91c#file-0-bridging-react-native-cheatsheet-md)