react native: how to unregister a listener/service?

Loading...

react native: how to unregister a listener/service?

I've a list of items. Each item can be displayed in MyComponent, by passing it's itemId. To listen on changes of the selected item, I'm passing myService:


The component fetches the item details and starts listening to the service:
componentDidMount() {
    this.fetchItemDetails(this.props.id); // fetch the item details

    this.props.myService.listensTo('eventId', () => { 
        // something changed, fetch again ... 
    });
}

componentWillUnmount() {
    // reset / unregister the listener for this instance 
}

Problem: the listener is registered everytime I mount MyComponent, which becomes a problem with multiple instances.
I'd like to listen only to the active, mounted component and unlisten as soon as it's unmounted. 
Any ideas?
Thanks in advance!

Solutions/Answers:

Answer 1:

You have to keep a reference to the function that you are using as callback. Usually what event listeners do is keep an internal structure of all the callback functions that have to be invoked when an event happens, and so, when you want to stop listening, you have to tell the event dispatcher which is the function that has to be excluded from the list. Since the only thing that gives you that information is the reference to the callback function itself. I would do the following:

constructor(){
    super();
    this.myListener = this.myListener.bind(this); // Do this only if necessary
}

componentDidMount() {
    this.fetchItemDetails(this.props.id); // fetch the item details

    this.props.myService.listensTo('eventId', myListener);
}

myListener(){
    //...
}

componentWillUnmount() {
   // reset / unregister the listener for this instance
   this.props.myService.deregister('eventId', myListener);
}

The important thing is to keep the reference to the function, that’s why it is important to put the binding in the constructor.

References

Loading...