Skip to content Skip to sidebar Skip to footer

Remove Event Listener That Has Been Added Using Bind(this)

How do I remove the click listener I bound to window in the constructor below? I need it to listen on window, and I need access to the button instance inside it.

Solution 1:

It's not possible with your current implementation - every call of .bind creates a new separate function, and you can only call removeEventListener to remove a listener if the passed function is the same (===) as the one passed to addEventListener (just like .includes for arrays, or .has for Sets):

constfn = () => 'foo';
console.log(fn.bind(window) === fn.bind(window));

As a workaround, you could assign the bound function to a property of the instance:

classMyElextendsHTMLButtonElement {
  constructor() {
    super();
    this.clickCount = 0;
    this.boundListener = this.clickHandler.bind(this);
    window.addEventListener('click', this.boundListener);
  }
  
  clickHandler(e) {
    this.textContent = `clicked ${++this.clickCount} times`;
    window.removeEventListener('click', this.boundListener);
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });
<buttonis="my-el"type="button">Click me</button>

Solution 2:

Create a wrapper func for your clickHandler like so.

classMyElextendsHTMLButtonElement {
  constructor() {
    super();
    this.clickCount = 0;
    this.wrapper = e =>this.clickHandler.apply(this, e);
    window.addEventListener('click', this.wrapper);
  }
  
  clickHandler(e) {
    this.textContent = `clicked ${++this.clickCount} times`;
    
    window.removeEventListener('click', this.wrapper);
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });
<buttonis="my-el"type="button">Click me</button>

Solution 3:

Another pattern is to keep your Listener inside the constructor.

To remove an Event Listener (no matter what pattern) you can add a 'remove' function the moment you create an Event Listener.

Since the remove function is called within the listen scope, it uses the same name and function

pseudo code:

listen(name , func){
    window.addEventListener(name, func);
    return() =>window.removeEventListener( name , func );
  }

  let remove = listen( 'click' , () =>alert('BOO!') );

  //cleanup:remove();

Run Code Snippet below to see it being used with multiple buttons

Events bubbling UP & shadowDOM

to save you an hour once you do more with events...

Note that WebComponents (ie CustomElements with shadowDOM) need CustomEvents with the composed:true property if you want them to bubble up past its shadowDOM boundary

newCustomEvent("check", {
      bubbles: true,
      //cancelable: false,
      composed: true// required to break out of shadowDOM
    });

Removing added Event Listeners

Note: this example does not run on Safari, as Apple refuses to implement extending elements : extends HTMLButtonElement

classMyElextendsHTMLButtonElement {
  constructor() {
    letME = super();// super() retuns this scope; ME makes code easier to readlet count = 0;// you do not have to stick everything on the ElementME.mute = ME.listen('click' , event => {
      //this function is in constructor scope, so has access to ALL its contentsif(event.target === ME) //because ALL click events will fire!ME.textContent = `clicked ${ME.id}${++count} times`;
      //if you only want to allow N clicks per button you call ME.mute() here
    });
  }

  listen(name , func){
    window.addEventListener( name , func );
    console.log('added' , name , this.id );
    return() => { // return a Function!console.log( 'removeEventListener' , name , 'from' , this.id);
      this.style.opacity=.5;
      window.removeEventListener( name , func );
    }
  }
  eol(){ // End of Lifethis.parentNode.removeChild(this);
  }
  disconnectedCallback() {
      console.log('disconnectedCallback');
      this.mute();
  }
}

customElements.define('my-el', MyEl, { extends: 'button' });
button{
  width:12em;
}
<buttonid="One"is="my-el"type="button">Click me</button><buttononclick="One.mute()">Mute</button><buttononclick="One.eol()">Delete</button><br><buttonid="Two"is="my-el"type="button">Click me too</button><buttononclick="Two.disconnectedCallback()">Mute</button><buttononclick="Two.eol()">Delete</button>

Notes:

  • count is not available as this.count but is available to all functions defined IN constructor scope. So it is (kinda) private, only the click function can update it.

  • onclick=Two.disconnectedCallback() just as example that function does NOT remove the element.


Also see: https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/

Post a Comment for "Remove Event Listener That Has Been Added Using Bind(this)"