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;
}