React: Remove event listener used with bind in ES6 syntax ?

Created on 9 Feb 2016  ·  3Comments  ·  Source: facebook/react

I'm trying to communicate with an iframe with the postMessage API but I have an issue with the eventListeners management in ES6

It is stated in the docs that

With React, every method is automatically bound to its component instance (except when using ES6 class syntax)

The problem is that this.handler.bind(this) !== this.handler so when I'm done with the event I can't remove the listener because I can't keep a reference to the handler. I could try to encapsulate the function, but the encapsulating function would also need a binding. I could try to super the constructor too but I'm not sure this is a good idea, plus I don't know the args it need. I'm quite sure I'm missing an important point here.

Any help would be much appreciated !

export default class SomeComponent extends Component {

  handleIframeData(event) {
    // some stuff in there that will need 'this' to be set to the component's context, to get props for example.
  }

  componentDidMount() {
    window.addEventListener('message', this.handleIframeData.bind(this), false)
  }

  componentWillUnmount() {
    // won't work because 'this.handleIframeData.bind(this) !== this.handleIframeData'
    window.removeEventListener('message', this.handleIframeData, false)
  }

  render() {
    return (
      <div className="SomeComponent" style={{height: '100%', width:'100%', display: 'table'}}>
        <iframe src="assets/iframe/index.html" style={{display: 'table-row', width: '100%', height:'100%', border: 0}}></iframe>
      </div>
    )
  }
}

Thanks anyway !

Question

Most helpful comment

The issue tracker is for bugs with React, not for general support. Use Stack Overflow or IRC for that.

That being said, the generic solution to this problem is to keep a reference to the bound handler around. E.g. you can bind the method in the constructor:

constructor(props) {
  super(props);
  this.handleIframeData = this.handleIframeData.bind(this);
}

See also the blog post that introduced classes: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding .

All 3 comments

The issue tracker is for bugs with React, not for general support. Use Stack Overflow or IRC for that.

That being said, the generic solution to this problem is to keep a reference to the bound handler around. E.g. you can bind the method in the constructor:

constructor(props) {
  super(props);
  this.handleIframeData = this.handleIframeData.bind(this);
}

See also the blog post that introduced classes: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding .

@fkling That's exactly what I was going to say :P. Correct on all points. Thanks!

Sry for that, thanks again !

Was this page helpful?
0 / 5 - 0 ratings