Skip to content

Commit

Permalink
Use event.composedPath() for event delegation.
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza committed Nov 22, 2023
1 parent 70c438c commit d218fe1
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/twelve-moles-mate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@chialab/dna': patch
---

Use `event.composedPath()` for event delegation.
6 changes: 3 additions & 3 deletions src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ export const delegateEventListener = (
if (!event.target) {
return;
}
const eventTarget = event.target as Node;
// wrap the Event's stopPropagation in order to prevent other delegations from the same root
const originalStopPropagation = event.stopPropagation;
const originalImmediatePropagation = event.stopImmediatePropagation;
Expand All @@ -188,13 +187,14 @@ export const delegateEventListener = (
const { selector, callback } = descriptors[i];
let selectorTarget;
if (selector) {
let target = eventTarget;
const path = event.composedPath();
let target = path.shift();
while (target && target !== element) {
if (isElement(target) && target.matches(selector)) {
selectorTarget = target;
break;
}
target = target.parentNode as Node;
target = path.shift();
}
} else {
selectorTarget = element;
Expand Down
35 changes: 35 additions & 0 deletions test/events.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,41 @@ describe(
DNA.undelegateEventListener(wrapper, 'click', 'button', false);
}).toThrow(TypeError, 'The provided callback must be a function');
});

it('should delegate listeners to slotted contents', () => {
const callback = vi.fn();
const is = getComponentName();
const TestElement = DNA.define(
is,
class extends DNA.Component {
static get listeners() {
return {
'click .button_wrapper': this.prototype.method,
};
}

render() {
return DNA.html`<div class="button_wrapper"><slot /></div>`;
}

method(event, target) {
event.preventDefault();
callback(event.type, target.tagName);
}
}
);

const element = new TestElement();
wrapper.appendChild(element);

const button = document.createElement('button');
element.appendChild(button);

expect(callback).not.toHaveBeenCalled();
button.click();
expect(callback).toHaveBeenCalled();
expect(callback).toHaveBeenCalledWith('click', 'DIV');
});
});

describe('listeners getter', () => {
Expand Down

0 comments on commit d218fe1

Please sign in to comment.