Mussé Redi
Mussé Redi

Reputation: 945

Triggering eventListeners in JavaScript

By use of Chrome's API we can use the function

getEventListeners(object) 

to obtain all eventListeners of a certain DOM object.

How would one now go about triggering the acquired mouseClick events after iteration?

Upvotes: 0

Views: 964

Answers (1)

zero298
zero298

Reputation: 26877

You can create and dispatch Events whenever you want. Consider the following example. Since this snippet runs in a browser context, we can't actually use getEventListeners().

// Get an element
const test = document.querySelector(".test");

// Add a listener
test.addEventListener("click", () => console.log("test"));

// Trigger the listener
setTimeout(() => test.click(), 1000);

// Explicit event dispatching
setTimeout(() => {
  const evt = new Event("click");
  test.dispatchEvent(evt);
}, 2000);

// Create and dispatch events of every typ attached to element
if (typeof getEventListeners !== "function") {
  console.warn("getEventListeners is unsupported");
} else {
  Object.keys(getEventListeners(test)).forEach(k => {
    const e = new Event(k);
    test.dispatchEvent(e);
  });
}
<div class="test">Hello</div>

So, to boil all that down into a reusable function, we can write:

/**
 * Dispatch events for all listeners attached to an element
 * @param {Element} el The element to dispatch events for
 */
function fireAllListeners(el) {
  /* 
   * getEventListeners only works in console, so make 
   * sure we can call it without throwing an exception
   */
  if (typeof getEventListeners !== "function") {
    console.warn("getEventListeners is not supported in this context");
    return
  }

  // Get all the listeners on an element
  const listeners = getEventListeners(el);
  // Get all the types of listeners ("click", "touch", "load", etc)
  const listenerTypes = Object.keys(listeners);
  // Map those listeners and make events for each
  const eventsToFire = listenerTypes.map(lt => new Event(lt));

  // Dispatch all the events
  eventsToFire.forEach(e => el.dispatchEvent(e));
}

Upvotes: 2

Related Questions