Skip to content

Commit

Permalink
addListener(): Allow for null | undefined targets. Created new `noo…
Browse files Browse the repository at this point in the history
…p()` helper.
  • Loading branch information
alexiglesias93 committed Oct 18, 2022
1 parent 6cb3089 commit 9465c47
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
6 changes: 6 additions & 0 deletions .changeset/shy-plants-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@finsweet/ts-utils': minor
---

- `addListener()`: Allow for null | undefined targets. If that's the case, no events will be added and the return callback will be a simple `noop`.
- Created new `noop()` helper, it literally does nothing.
11 changes: 10 additions & 1 deletion src/helpers/addListener.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { noop } from './noop';

/**
* Adds an event listener to an element.
* @returns A callback to remove the event listener from the element.
Expand Down Expand Up @@ -25,7 +27,14 @@ export function addListener<
: Type extends keyof ElementEventMap
? (this: Element, ev: ElementEventMap[Type]) => unknown
: EventListenerOrEventListenerObject
>(target: TargetInterface, type: Type, listener: Listener, options?: boolean | AddEventListenerOptions): () => void {
>(
target: TargetInterface | null | undefined,
type: Type,
listener: Listener,
options?: boolean | AddEventListenerOptions
): () => void {
if (!target) return noop;

target.addEventListener(type, listener, options);

return () => target.removeEventListener(type, listener, options);
Expand Down
1 change: 1 addition & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export { getObjectEntries } from './getObjectEntries';
export { getObjectKeys } from './getObjectKeys';
export { isScrollable } from './isScrollable';
export { isVisible } from './isVisible';
export { noop } from './noop';
export { queryElement } from './queryElement';
export { removeChildElements } from './removeChildElements';
export { removeSpaces } from './removeSpaces';
Expand Down
7 changes: 7 additions & 0 deletions src/helpers/noop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* eslint-disable @typescript-eslint/no-empty-function */

/**
* No operation.
* It literally does nothing.
*/
export const noop = () => {};

0 comments on commit 9465c47

Please sign in to comment.