ESP32
ESP32

Reputation: 8728

How to avoid that .click() adds new listeners every time it is used

I have function which adds event listeners (.click(...)) to some elements (among many other tasks).

I need to call this function multiple times (for example on window resize). Each time I call this function the listeners are added again - so if I call my function 3 times, each click will fire 3 times instead of one time.

I have build a simplyfied example: https://plnkr.co/edit/5NmIruVoAknfcrRTBSYb

  var clickMe = $("#clickme");
  function init() {
    setTimeout(function() {
      clickMe.click(function() {
        $("#output").append(".");
      })
    }, 100)
  }

  init();

  $("#recall").click(function() {
    init();
  });

Of course this sample (and the setTimeout) does not make sense, but it reflects my code block best. Is it possible to closure the whole init function in a way that the everything is reset if I call it? Or do I have to remove the events with unbind() every time?

Upvotes: 1

Views: 38

Answers (1)

Rob Branaghan
Rob Branaghan

Reputation: 74

I had a look at your code and I think this is a fix

If you Remove the click event

.off("click")

then you can add it back in again, this will always remove it if it exists before adding it.

.off("click").on("click", function() {

The following is the changed javascript

$(document).ready(function() {
  init();
  var clickMe = $("#clickme");
  function init() {
    setTimeout(function() {
      clickMe.off("click").on("click", function() {
      $("#output").append(".");
      })
    }, 100)
   }
 $("#recall").click(function() {
   init();
 }); 
})

Upvotes: 1

Related Questions