i wanted to check if the event listener is already attached to the window using javascript or react.
what i am trying to do?
i have a dropdown menu component and in its didupdate hook cycle if the dropdown menu is open i add scroll event listener and on unmount hook cycle i remove the scroll event listener.
but in didupdate hook i add scroll event only if the condition this.props.open && !prevState.open is true....
but i dont remove the eventlistener scroll if this condition is false.
how can i do it....
below is the code,
componentDidUpdate(prevProps, prevState) {
if (this.props.open && !prevState.open) {
window.addEventListener('scroll', this.handle_scroll, {capture: true, passive: true});
} else {
//i want to remove scroll eventlistener here if its already added
}
}
componentWillUnmount () {
window.removeEventListener('scroll', this.handle_scroll, {capture: true, passive: true});
}
handle_scroll = () => {
requestAnimationFrame(this.call_some_method);
};
What i have tried
componentDidUpdate(prevProps, prevState) {
if (this.props.open && !prevState.open) {
window.addEventListener('scroll', this.handle_scroll, {capture: true, passive: true});
} else {
window.removeEventListener('scroll', this.handle_scroll, {capture: true, passive: true});
}
}
But as seen from above code....it adds the scroll event listener only when the props.open && !prevState.open is true... and i remove the eventlistener when this is condition is false...and i want it to remove eventlistener when this.props.open && !prevState.open is false && scrollevent listener is added to window.
How can i do it. could someone help me with this. thanks.