我不能为我的生活得到一个事件,从iOS本机跨桥到适当的原生JS上下文正确发送.在Objective-C方面,我希望有一个模块可以轻松地在桥上发送事件.我已经调用了这个类EventEmitter,它的定义如下:
// EventEmitter.h #import "RCTBridge.h" #import "RCTEventDispatcher.h" @interface EventEmitter : NSObject<RCTBridgeModule> - (void)emitEvent:(NSString *) eventName withData:(id) eventData; @end
和实施:
// EventEmitter.m #import "EventEmitter.h" @implementation EventEmitter RCT_EXPORT_MODULE(); @synthesize bridge = _bridge; - (void)emitEvent:(NSString *) eventName withData:(id) eventData { NSLog( @"emitting %@ with data %@",eventName,[eventData description] ); [[_bridge eventDispatcher] sendDeviceEventWithName:eventName body:eventData]; [[_bridge eventDispatcher] sendAppEventWithName:eventName body:eventData]; } @end
我正在使用sendDeviceEvent和sendAppEvent,因为我无法工作.
在JS方面,我注册在我的一个模块的全局命名空间中接收这些事件(这样我就知道事件订阅将在事件发出之前发生).我这样注册:
console.log( 'ADDING EVENT LISTENERS' ); NativeAppEventEmitter.addListener( 'blah',test => console.log( 'TEST1',test ) ); DeviceEventEmitter.addListener( 'blah',test => console.log( 'TEST2',test ) );
在我的日志语句中,我得到以下内容:
2016-03-19 12:26:42.501 [trace][tid:com.facebook.React.JavaScript] ADDING EVENT LISTENERS 2016-03-19 12:26:43.613 [name redacted][348:38737] emitting blah with data [data redacted]
所以我可以告诉我发送了一个app事件和一个带有标签blah的设备事件,我已经注册了用DeviceEventEmitter和NativeAppEventEmitters来监听blah事件,但是我没有在监听器中回调.
我究竟做错了什么??谢谢阅读!
解决方法
我已经尝试调度事件,当你使用[EventEmitter alloc] init]手动创建新的EventEmitter实例时,似乎没有初始化桥接器
你应该让react-native创建实例.我检查了原生组件,他们正在使用 – (void)setBridge:(RCTBridge *)桥接方法进行初始化工作.请查看RCTLinkingManager以查看示例.它使用NSNotificationCenter来处理事件.
// registering for RCTOpenURLNotification evet when the module is initialised with a bridge - (void)setBridge:(RCTBridge *)bridge { _bridge = bridge; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURLNotification:) name:RCTOpenURLNotification object:nil]; } // emitting openURL event to javascript - (void)handleOpenURLNotification:(NSNotification *)notification { [_bridge.eventDispatcher sendDeviceEventWithName:@"openURL" body:notification.userInfo]; } // creating RCTOpenURLNotification event to invoke handleOpenURLNotification method + (BOOL)application:(UIApplication *)application openURL:(NSURL *)URL sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { NSDictionary<NSString *,id> *payload = @{@"url": URL.absoluteString}; [[NSNotificationCenter defaultCenter] postNotificationName:RCTOpenURLNotification object:self userInfo:payload]; return YES; }