-
-
Save channyeintun/9c449dfb7aca6c9981502a8240fb2b64 to your computer and use it in GitHub Desktop.
Records DOM-events and replays them on demand. Nice for server side rendered pages: record during page-load, replay after all javascript was initialized.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* EventRecorder | |
* @class | |
* @classdesc An EventRecorder can record and replay any event on any DOM node | |
* @param {string} [eventName=click] - Name of the events to record | |
* @param {class} [EventClass=MouseEvent] - The class that should be used to recreate the events | |
* @param {object} [context=self] - The context DOM element, the events should be fetched from | |
* @example | |
* // Create a recorder for click events | |
* const clickRecorder = new EventRecorder('click', MouseEvent, window); | |
* // Start recording | |
* clickRecorder.record(); | |
* // Replay (and clean up) all recorded events on window.onload | |
* window.addEventListener('load', () => clickRecorder.replay()); | |
*/ | |
class EventRecorder { | |
queue = []; | |
constructor(eventName = "click", EventClass = MouseEvent, context = self) { | |
this.eventName = eventName; | |
this.EventClass = EventClass; | |
this.context = context; | |
} | |
addEventToQueue = e => { | |
this.queue.push(e); | |
}; | |
dispatchAll() { | |
this.queue.forEach(e => | |
e.target.dispatchEvent( | |
new this.EventClass(this.eventName, { | |
view: this.context, | |
bubbles: true, | |
cancelable: true | |
}) | |
) | |
); | |
} | |
cleanUp() { | |
this.queue.length = 0; | |
this.context.removeEventListener(this.eventName, this.addEventToQueue); | |
} | |
record() { | |
this.context.addEventListener(this.eventName, this.addEventToQueue); | |
} | |
replay() { | |
this.dispatchAll(); | |
this.cleanUp(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment