Skip to content Skip to sidebar Skip to footer

Confirming That Using A Factory Is The Best (only?) Way To Create A Generic Multi-use Click Count Listener

I have created the following click count factory for adding the click count to the event information already present in a regular click event. This function creates a clickCountObj

Solution 1:

For sure you can also use a class:

classClickCounter{
   constructor(element, onClick, delay = 500) {
     this.element = element;
     this.onClick = onClick;
     this.counter = 0;
     this.delay = delay;
     this.lastClicked = 0;

     element.addEventListener("click", () => this.click(), false);
  }

  click() {
    if(Date.now() < this.lastClicked + this.delay)
      return;
    this.lastClicked = Date.now();
    this.onClick.call(this.element, this.counter++);
  }
}

 new ClickCounter(document.body, count => {
   alert(count);
 });

[is] doing this a better way?

No, not really. Using a class is not really useful here as you don't want to expose properties and you also don't need inheritance. A factory seems to be a good approach here.

Small sidenote: Instead of

return clickCountListener;

it would make more sense to

return clickCountObj;

as it would expose the settings and the count which might be useful.


warning: unserious content below

Way back when I was working in Java ...

... you took over that senseless naming scheme (clickCountObj.clickCount). I guess you won't loose any necessary information with just settings.count ...

Post a Comment for "Confirming That Using A Factory Is The Best (only?) Way To Create A Generic Multi-use Click Count Listener"