夜一林风
夜一林风

Reputation: 1327

How to receive event callbacks using RCTEventEmitter in react-native

After updating react-native code from 0.28 to 0.30, subclassing RCTEventEmitter is the recommended way for sending events back to Javascript and the old way is deprecated.

- (void)startObserving{}

- (void)stopObserving{}

- (NSArray<NSString *> *)supportedEvents{

    return @[@"someInterestingEvent"];
}

-(void)interestingEventHappen{
    [self sendEventWithName:@"someInterestingEvent" body:nil];
}

The problem is how do I receive the callback rather than just registering the event. I notice RCTEventEmitter has method RCT_EXPORT_METHOD(addListener:(NSString *)eventName) exposed, but it only receives one argument(the event name). I tried the document:

NativeAppEventEmitter.addListener('someInterestingEvent', ()=>{});

with no results and the yellow box complaines sending someInterestingEvent with no listeners registered.

Did I miss something?

Upvotes: 6

Views: 12243

Answers (1)

夜一林风
夜一林风

Reputation: 1327

The question has already been discussed on github.

In short you have to use the NativeModules module to get this native module and wrap it in NativeEventEmitter class so that you can receive events.

import { NativeModules, NativeEventEmitter } from 'react-native'

const myModuleEvt = new NativeEventEmitter(NativeModules.MyModule)
myModuleEvt.addListener('sayHello', (data) => console.log(data))

Upvotes: 9

Related Questions