Skip to content

Commit

Permalink
fix: add an explicit check to bound element to work around monkey pat…
Browse files Browse the repository at this point in the history
…ching issues (#1839)

#1835
  • Loading branch information
zewa666 authored Feb 7, 2025
1 parent a062edb commit 7ccede6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
15 changes: 15 additions & 0 deletions packages/binding/src/__tests__/bindingEvent.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,21 @@ describe('BindingEvent Service', () => {
expect(addEventSpy).toHaveBeenCalledWith('click', mockCallback, undefined);
});

it('should not use forEach if the element is a single HTMLElement but with a monkey patched forEach', () => {
const elm = document.createElement('input');
div.appendChild(elm);
const forEachSpy = vi.fn();
(elm as any).forEach = forEachSpy;
const mockCallback = vi.fn();
const addEventSpy = vi.spyOn(elm, 'addEventListener');

service.bind(elm, 'click', mockCallback);

expect(service.boundedEvents.length).toBe(1);
expect(addEventSpy).toHaveBeenCalledWith('click', mockCallback, undefined);
expect(forEachSpy).not.toHaveBeenCalled();
});

it('should be able to bind and unbindByEventName an event', () => {
const mockElm = { addEventListener: vi.fn() } as unknown as HTMLElement;
const mockCallback = vi.fn();
Expand Down
5 changes: 4 additions & 1 deletion packages/binding/src/bindingEvent.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ export class BindingEventService {
// convert to array for looping in next task
const eventNames = Array.isArray(eventNameOrNames) ? eventNameOrNames : [eventNameOrNames];

if ((elementOrElements as NodeListOf<HTMLElement>)?.forEach) {
if (
!(elementOrElements instanceof HTMLElement || elementOrElements instanceof DocumentFragment) &&
(elementOrElements as NodeListOf<HTMLElement>)?.forEach
) {
// multiple elements to bind to
(elementOrElements as NodeListOf<HTMLElement>).forEach((element) => {
for (const eventName of eventNames) {
Expand Down

0 comments on commit 7ccede6

Please sign in to comment.