Skip to content

Commit

Permalink
Accept array of selectors (#53)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Aug 20, 2024
1 parent 5e68bc3 commit 99ea1f0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
7 changes: 7 additions & 0 deletions delegate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ test('should remove an event listener', () => {
expect(spy).toHaveBeenCalledTimes(0);
});

test('should handle multiple selectors', () => {
const spy = vi.fn();
delegate(['a', 'b'], 'click', spy);
anchor.click();
expect(spy).toHaveBeenCalledTimes(1);
});

test('should not add an event listener of the controller has already aborted', () => {
const spy = vi.fn();
delegate('a', 'click', spy, {signal: AbortSignal.abort()});
Expand Down
8 changes: 4 additions & 4 deletions delegate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function delegate<
TElement extends Element = ParseSelector<Selector, HTMLElement>,
TEventType extends EventType = EventType,
>(
selector: Selector,
selector: Selector | Selector[],
type: TEventType,
callback: DelegateEventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions
Expand All @@ -83,7 +83,7 @@ function delegate<
TElement extends Element = HTMLElement,
TEventType extends EventType = EventType,
>(
selector: string,
selector: string | string[],
type: TEventType,
callback: DelegateEventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options?: DelegateOptions
Expand All @@ -94,7 +94,7 @@ function delegate<
TElement extends Element,
TEventType extends EventType = EventType,
>(
selector: string,
selector: string | string[],
type: TEventType,
callback: DelegateEventHandler<GlobalEventHandlersEventMap[TEventType], TElement>,
options: DelegateOptions = {},
Expand All @@ -114,7 +114,7 @@ function delegate<
// Handle the regular Element usage
const capture = Boolean(typeof options === 'object' ? options.capture : options);
const listenerFunction = (event: Event): void => {
const delegateTarget = safeClosest(event, selector);
const delegateTarget = safeClosest(event, String(selector));
if (delegateTarget) {
const delegateEvent = Object.assign(event, {delegateTarget});
callback.call(baseElement, delegateEvent as DelegateEvent<GlobalEventHandlersEventMap[TEventType], TElement>);
Expand Down

0 comments on commit 99ea1f0

Please sign in to comment.