0

I am working on mobile app with React Native and have discovered this weird behaviour using EventEmitter in my project. I am using Flux. In my Scene (Component) I listen to Event as seen below in code:

Component:

componentWillMount(){
  BasketStore.addChangeListener(this._onChange.bind(this));
}

componentWillUnmount(){
  BasketStore.removeChangeListener(this._onChange.bind(this));
}

BaseStore:

export default class BaseStore extends EventEmitter {
  constructor() {
    super();
  }

  emitChange() {
    this.emit(CHANGE_EVENT);
  }

  addChangeListener(callback) {
    this.on(CHANGE_EVENT, callback);
  }

  removeChangeListener(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }

  subscribe(actionSubscribe) {
    this._dispatchToken = AppDispatcher.register(actionSubscribe());
  }

  get dispatchToken() {
    return this._dispatchToken;
  }
}

BaskekStore:

class BasketStore extends BaseStore {...}

In Navigator I do navigator.pop() to go back in my route. From documentation it says that it should unmount my Component every time I do pop, which I use to go back in my previous scene. However it does not, and my Component still listens to _onChange event which make app behave wrong, the more I swap between views app becomes slow and eventually crush as there are too many views and listeners.

Thanks in advance!

George Mylonas
  • 704
  • 6
  • 16
  • I haven't used react for mobile development, so my info might be off base.... but I don't think you need to bind `this` to your `_onChange` callback. The bind might make the function reference have a unique footprint, thus making your removeListener not pull out the callback. As a test, I would start by verifying if you hit the `componentWillUnmount` at all (I think you are), which should narrow the scope to indeed be an issue with the removeListener. – Jake Haller-Roby Feb 24 '16 at 21:51
  • I had tried it before without `this` and it does not work. It actually can't find the callback function in the event Listener. Binding `this` tells to `EventEmitter` that `_onChange` comes from `Component Class` and it is not part of `EventEmitter`. `componentWillUnmount` does work and I did a `GenericComponent` which I tried to extend and have a `_uniqueID` = `Math.random()` and `_isMounted` which is triggered on Mount and Unmount, so before I use `setState({...})` it will check it. Did work, but app is very laggish as too many Components are mounted. I found a solution and will posted later. – George Mylonas Feb 26 '16 at 10:31
  • I found a solution. Will post it later. ReactNative has a bug and actually does not unmount components. It will be fixed in v.0.21 (they said). – George Mylonas Feb 26 '16 at 10:32

0 Answers0