如何从React Native的EventEmitter实例中删除监听器?

时间:2016-04-27 10:04:55

标签: react-native event-handling

removeCurrentListener,但没有removeListener方法。

2 个答案:

答案 0 :(得分:27)

我自己找到了答案。

https://github.com/facebook/react-native/blob/235b16d93287061a09c4624e612b5dc4f960ce47/Libraries/vendor/emitter/EventEmitter.js

addListener返回EmitterSubscription个实例,该实例扩展EventSubscriptionremove方法。

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

答案 1 :(得分:3)

实际上确实如此(除非我误解了你的问题)。

以下是我的表现方式:

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)
    }
}