Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove a listener from React Native's EventEmitter instance?

There is removeCurrentListener, but no removeListener method.

like image 255
Joon Avatar asked Apr 27 '16 10:04

Joon


2 Answers

I found the answer myself.

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

addListener returns a EmitterSubscription instance that extends EventSubscription that has remove method.

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
like image 102
Joon Avatar answered Oct 19 '22 01:10

Joon


Actually it does (unless I'm misunderstanding your question).

Here's how I do it:

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)
    }
}
like image 38
Naoto Ida Avatar answered Oct 19 '22 01:10

Naoto Ida