有removeCurrentListener
,但没有removeListener
方法。
我自己找到了答案。
https://github.com/facebook/react-native/blob/235b16d93287061a09c4624e612b5dc4f960ce47/Libraries/vendor/emitter/EventEmitter.js
addListener
返回一个EmitterSubscription
实例,该实例扩展了具有remove
方法EventSubscription
。
https://github.com/facebook/react-native/blob/235b16d93287061a09c4624e612b5dc4f960ce47/Libraries/vendor/emitter/EventSubscription.js
const emitter = new EventEmitter();
const subscription = emitter.addListener('eventname', () => {});
subscription.remove(); // Removes the subscription
实际上确实如此(除非我误解了你的问题)。
这是我的做法:
class Store extends EventEmitter {
constructor(listenerKey) {
super()
this.listenerKey = listenerKey
}
emitChange() {
setTimeout(() => {
this.emit(this.listenerKey)
}, 0)
}
addChangeListener(callback) {
this.on(this.listenerKey, callback)
}
removeChangeListener(callback) {
this.removeListener(this.listenerKey, callback)
}
}