Reputation: 801
I'm using react-redux and have a chat application in the webapp. I want to be able to dispatch an action when the user closes the web browser, closes the tab, or changes to another website. I've looked around and tried this:
componentWillMount() {
// run once before first render()
this.props.initializeApp();
this.dispatchActionOnExit = this.dispatchActionOnExit.bind(this);
}
componentDidMount() {
window.addEventListener("unload", this.dispatchActionOnExit());
}
dispatchActionOnExit() {
// dispatch the action when exit
}
componentWillUnmount() {
window.removeEventListener("unload", this.updateWindowDimensions);
}
But I don't understand what this line does:
this.dispatchActionOnExit = this.dispatchActionOnExit.bind(this);
Also, I'm not sure if this is the best solution.
Any help is appreciated; thanks in advance. :)
Upvotes: 1
Views: 880
Reputation: 651
so the line this.dispatchActionOnExit = this.dispatchActionOnExit.bind(this);
simply binds the this
context of whichever react components you have this code in. So that no matter where/when you call dispatchActionOnExit
its this
context will still be to the react component where you bound it. See MDN Documentation on Function.prototype.bind.
Upvotes: 2