0

I use ES6 class syntax, React.js and Flux for my project. This is a piece of the code:

export default class Splash extends React.Component {

  constructor() {
    super();
    this.state = Comm.reqSplash();
  }

  componentDidMount(){
    this._appReadyBound = this._appReady.bind(this);
    SplashStore.subscribe(this._appReadyBound);
  }

  //Trigger when app data is loaded, if splash is in non-intro mode then end splash
  _appReady(){
    SplashStore.unsubscribe(this._appReadyBound);
    //If intro mode, do nothing
    if (this.state.mode !== "non-intro") return;
    this.endSplash();
  }
}

As you can see, in "componentDidMount" method, I have to create a bound version of "_appReady" method.

If I don't bind with "this", "_appReady" method won't behave correctly. If I don't make a bound version, the unsubscribe method, which is the same as "removeChangeListener" if you are more familiar with it, will not do its job, which means the listener is still on the listener list.

So I'm wondering if there is an elegant way to do the binding thing, or avoid binding. Or maybe I should abandon ES6 class syntax?

  • possible duplicate of [can i use ES6 fat arrow in class methods?](http://stackoverflow.com/a/31368520/1048572) or [React, “this”, cloneElement and es6](http://stackoverflow.com/q/31841949/1048572)? Let me know if any of them helped you – Bergi Sep 16 '15 at 11:55

1 Answers1

1

Have you tried

_appready = () => {
  //function here

}

Hope it helps

François Richard
  • 6,817
  • 10
  • 43
  • 78