Verifying that utilizing a factory is the most effective method for developing a versatile click count listener

In my quest to enhance the functionality of click events, I have devised a click count factory. This factory creates a clickCountObj to keep track of the number of clicks and implements a new function for capturing click events on a specified element and relaying the information back to the listener along with the click count.

Initially, I pondered implementing this as a class rather than a factory. Back in my Java days, I would have utilized a façade class to accomplish this task. However, after delving into Javascript, I realized that it is not feasible because the same function used to create the object would also be triggered upon a click event – presenting an insurmountable obstacle.

This inquiry serves the purpose of refining my comprehension and utilization of JavaScript. Kindly enlighten me if my earlier assumption is flawed or if there exist more efficient alternatives to achieve the desired outcome?

function clickCount(element, listener) {
  let clickCountObj = {};
  clickCountObj.clickCount = 0;
  clickCountObj.clickDelay = 500;
  clickCountObj.element = element;
  clickCountObj.lastClickTime = 0;
  let clickCountListener = function (e) {
//    alert("last click time: " + clickCountObj.clickDelay);
    if ((e.timeStamp - clickCountObj.clickDelay) < clickCountObj.lastClickTime) {
      clickCountObj.clickCount = clickCountObj.clickCount + 1;
//      alert("click count up: " + clickCountObj.clickCount);
    }
    else {
      clickCountObj.clickCount = 1;
    }
    clickCountObj.lastClickTime = e.timeStamp;
    listener.call(element, clickCountObj.clickCount, e);
  };
  if (!element) throw "No element to listen to";
  element.addEventListener("click", clickCountListener);
  return clickCountListener;
}

Answer №1

Of course, you have the option to utilize a class in this scenario:

 class ClickCounter {
   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?

In this case, no. The usage of a class might not be essential since there is no need for property exposure or inheritance. Implementing a factory pattern could be more suitable.

On a side note: Instead of

 return clickCountListener;

it may be more logical to

 return clickCountObj;

as it would provide access to both settings and the count, potentially proving valuable.


warning: unserious content below

Reminiscing about my days coding in Java ...

... you embraced that pointless naming convention (clickCountObj.clickCount). Simplifying it to just settings.count wouldn't result in any lost information...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

Trouble with Mocha async hooks execution?

I keep encountering the issue of receiving 'undefined' for the page in this setup. It appears that none of Mocha's hooks are being executed. I've attempted adding async to the describe at the top level, used done statements, and even tr ...

Is there anyone available to assist me with this contact validation form?

I'm struggling to make this contact form highlight red and display 'not valid' inside the boxes. Despite my efforts, I just can't seem to get it to work! I'm unable to change the existing HTML tags, but I can add to the HTML. I wan ...

The function you are trying to access does not exist in this.props

Trying to pass this.state.user to props using the isAuthed function is resulting in an error: this.props.isAuthed is not a function . The main objective is to send this.state.user as props to App.js in order to show or hide the Sign out button based on ...

Verification of JQuery UI Dialog Prompt using the Enter key

I have attempted the methods recommended in a stack answer but to no avail: Submit jQuery UI dialog on <Enter> There seems to be an issue with my code. Upon logging in, a disclaimer appears to notify users that the content within the site is confid ...

'view' is not recognized as a valid property of the 'div' element in Ionic3, so it cannot be bound

I am a beginner with Ionic and I'm trying to incorporate Angular Calendar into my Ionic3 application. However, I am encountering an error that says, "Can't bind to 'view' since it isn't a known property of 'div'. Here&ap ...

React does not always remove event listeners when using the useEffect hook's return callback

I have a functionality in my component where it initializes a key event listener. This event is supposed to trigger an API call to fetch random data. useEffect(() => { const keyUpEvent = (event) => { if (event.code === "Enter") { ...

Is there a way to extract rows from a React MUI DataGrid that are identical to how they are displayed, including any filtering and sorting applied?

My goal is to make a selected row move up and down on arrow clicks, and in order to achieve this, I need to retrieve rows from the MUI DataGrid. I am using the useGridApiRef hook to do so, ensuring that the rows are filtered and sorted accordingly to match ...

Error message in JS/Ajax alert box

I keep receiving an alert box saying "Image uploaded" even when the variable $imagename is empty. Below is the script in question: <script> function ajax_post1(ca){ var cat = ca; var name = document.getElementById("name").value; var ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

Click on the react item to view more information

I'm brand new to React and I'm exploring the swapi API for the first time. My goal is to retrieve a list of films (movie titles) and then, when a title is clicked on, display the opening crawl from the JSON object. So far, I've been able to ...

Tips for showcasing an item with the chosen value in a dropdown menu

Below is the object I created: export default { data() { return { language: { "en": { welcomeMsg: "Welcome to New York City" }, "de": { ...

How can I create distinct component IDs effectively with the Catberry Framework?

When working with Catberry, it is essential that all components have unique IDs. How can you ensure that each ID remains distinctive even within a complex structure of nested components? ...

Creating dropdown options within a DataGrid in Form.IO: A step-by-step guide

I'm currently working with the Form.IO JS library to develop a new form. Within this form, I need to include a DataGrid containing 11 components. To ensure all components fit inline, I have applied the CSS rule overflow: auto (overflow-x: auto; overfl ...

Crafting LayerGroups on the Fly with Leaflet

Dynamic Creation of LayerGroups: Is it Achievable? I am currently working on a web map showcasing the various tree species present in parks. My goal is to create a separate LayerGroup for each species so that users can toggle visibility using a LayerContro ...

Exploring the wonders of Vue.js and Laravel's type casting techniques

I have implemented DB2-style IDs for my database records in my Laravel 5.7 application, like this example: 201402241121000000000000. When trying to use it in my Vue component, I used the following syntax: <mycomponent v-bind:listing-key="{{ $listing-&g ...

Guide to flattening a nested array within a parent array using lodash

Within my array named sports, there is another array called leagues, but I need to flatten these arrays using _.flatten due to issues with Angular filters. If you look at the data, inside the first array which contains a "name":"Live Betting", there is an ...

Remain on the current webpage following the submission of comparable ajax-forms

Seeking assistance with an issue involving Ajax that I believe is unique. Desired Outcome I have a newsfeed with various posts and interspersed forms, such as polls, for user interaction and submission of results. Objectives Users should be able to inter ...

Keep the Bootstrap modal open while the JavaScript validation is running, and redirect the form action if the validation is successful

When trying to execute the submit event from a form, my code is supposed to keep the modal open if validation fails. However, for some reason, this functionality is not working as expected. var myForm = document.updteform; var condition = true; if ...

Ways to extract values from a JSON output using comparisons

I am dealing with a JSON data structure that contains information about various teams. My task is to compare the values in the teams array with the values stored in html_content.position[i]. In this comparison, the index i needs to be dynamically set withi ...