Skip to content

Instantly share code, notes, and snippets.

@jkempff
Created May 11, 2018 16:17
Show Gist options
  • Save jkempff/8b907835dd93234eb012079054b8f933 to your computer and use it in GitHub Desktop.
Save jkempff/8b907835dd93234eb012079054b8f933 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.
/**
* 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