引入
import { DeviceEventEmitter } from 'react-native'
添加监听
/**
* @param {string} eventType - Name of the event to listen to
* @param {function} listener - Function to invoke when the specified event is
* emitted
* @param {*} context - Optional context object to use when invoking the
* listener
*/
addListener( eventType: string, listener: Function, context: ?Object)
例:
async componentDidMount() {
//路由监听
this.subscription = DeviceEventEmitter.addListener('userInfoChange', () =>
this.getMyInfo(),
);
}
once一次性监听
/**
* @param {string} eventType - Name of the event to listen to
* @param {function} listener - Function to invoke only once when the
* specified event is emitted
* @param {*} context - Optional context object to use when invoking the
* listener
*/
once(eventType: string, listener: Function, context: ?Object)
removeAllListeners - 移除所有的事件监听
// 移除指定类型的事件监听
DeviceEventEmitter.removeAllListeners(eventType: ?string)
// 移除所有的事件监听
DeviceEventEmitter.removeAllListeners()
removeListener - 移除指定事件类型的监听
/**
*
* @param {string} eventType - Name of the event to emit
* @param {function} listener - Function to invoke when the specified event is
* emitted
*/
DeviceEventEmitter.removeListener('someEvent', function(message) {
console.log(message);
}); // removes the listener if already registered
removeCurrentListener - 在事件回调调用期间移除监听
var subscription = DeviceEventEmitter.addListenerMap({
someEvent: function(data, event) {
console.log(data);
DeviceEventEmitter.removeCurrentListener();
}
});
DeviceEventEmitter.emit('someEvent', 'abc'); // logs 'abc'
DeviceEventEmitter.emit('someEvent', 'def'); // does not log anything
listeners - 返回指定事件类型的所有监听者
/**
* @param {string} eventType - Name of the event to query
* @returns {array}
*/
DeviceEventEmitter.listeners(eventType: string);
发送消息
DeviceEventEmitter.emit('userInfoChange');
DeviceEventEmitter.addListener('someEvent', function(message) {
console.log(message);
});
// 第二个参数是传递给Listener的arguments
DeviceEventEmitter.emit('someEvent', 'abc'); // logs 'abc'