0

I have a click event handler in my React component and wish to remove the event handler when hideLeft occurs, but am unable to do so with $(document).unbind('click', this.hideLeft.bind(this)). Currently can only remove the click event handler by doing $(document).unbind('click').

How can I avoid this and only remove click event handlers associated with the hideLeft function?

class Header extends Component {
    constructor(props, context) {
        super(props, context); 
        this.state = {
            panel_visible: false
        };
    }

    logOut() {
        console.log('logged out');
    }

    hideLeft(event) {
        if (!$(event.target).closest('.menu').length) {
            $(document).unbind('click');                      
            this.setState({
                panel_visible: false
            }); 
        }
    }

    showLeft() {
        this.setState({
            panel_visible: true
        });
        $(document).bind('click', this.hideLeft.bind(this));    
    }


    render() {
       return (
               <Sticky>
                    <header className='app-header'>
                      <LeftPanel visibility={this.state.panel_visible} showLeft={e => this.showLeft()} 
                        hideLeft={e => this.hideLeft()} />
                      <button onClick={e => this.showLeft()}>Show Left Menu!</button>
                      <button className='btn btn-default logout' onClick={e => this.logOut()}>Log Out</button>
                      <h1>Some header </h1>
                    </header>
               </Sticky>
           );
    }
}
2
  • I'm not sure what react code is here? The render method seems blank and event handlers can normally be handled with react code and not use jquery.
    – noveyak
    Oct 16, 2015 at 20:22
  • Hi @noveyak, I omitted the render method for simplicity as the event handlers had nothing to do with the render method
    – Yan Yi
    Oct 17, 2015 at 3:41

1 Answer 1

1

I'm doing this using vanilla js methods addEventListener and removeEventListener.

adding

document.addEventListener('click', this.hideLeft.bind(this));

removing:

document.removeEventListener('click', this.hideLeft.bind(this));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.