You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 !
The text was updated successfully, but these errors were encountered:
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:
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
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 !
Thanks anyway !
The text was updated successfully, but these errors were encountered: