Skip to content

Instantly share code, notes, and snippets.

@danielcaldas
Last active September 16, 2019 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielcaldas/b8540390f9b28db01def5028df2363f7 to your computer and use it in GitHub Desktop.
Save danielcaldas/b8540390f9b28db01def5028df2363f7 to your computer and use it in GitHub Desktop.
decorateAddEventListener.js
/**
* This is a DOM utility function that allows you to decorate a specific event handler
* for a specific event type of a DOM element with some additional behavior
* (e.g. for each click on a given button I want to log something before the actual click handler is executed).
* @param {Object} targetElement the target dom element whose addEventListener we want to decorate.
* @param {string} targetEventType the target event type whose event handler we want to decorate.
* @param {Function} decorator a function that returns the new event handler for the targetEventType.
* This returned function will most likely contain additional behavior.
* NOTE: make sure that your decorator function calls the actual event handler
* at the end, otherwise you will override the original behavior designed for that event
* handler, for that use `handler.apply(targetElement, [event]);`
*/
export function decorateAddEventListener(
targetElement,
targetEventType,
decorator,
) {
const _addEventListener = targetElement.addEventListener;
const decoratedAddEventListener = (eventType, handler) => {
let _handler = handler;
if (eventType === targetEventType) {
_handler = decorator(targetElement, targetEventType, handler);
}
_addEventListener.apply(targetElement, [eventType, _handler]);
};
targetElement.addEventListener = decoratedAddEventListener;
}
import { decorateAddEventListener } from '../decorateAddEventListener';
describe('decorateAddEventListener', () => {
it('should execute original event handler and increment counter from 0 to 1', () => {
let counter = 0;
const originalEventHandler = jest.fn();
const decorator = jest.fn(() => {
counter++;
originalEventHandler();
});
const addEventListener = jest.fn();
const targetEventType = 'click';
const targetElement = {
addEventListener,
};
decorateAddEventListener(targetElement, targetEventType, decorator);
targetElement.addEventListener(targetEventType, originalEventHandler);
expect(counter).toEqual(1);
expect(originalEventHandler).toHaveBeenCalled();
expect(decorator).toHaveBeenCalled();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment