Skip to content

Commit 15fa69b

Browse files
committed
Support events on elements that need to be handled by a unicorn parent.
1 parent 8f6fbcf commit 15fa69b

File tree

3 files changed

+43
-2
lines changed

3 files changed

+43
-2
lines changed

django_unicorn/static/js/element.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,26 @@ export class Element {
198198
return generateDbKey(this);
199199
}
200200

201+
/**
202+
* Get the element's next parent that is a unicorn element.
203+
*
204+
* Returns `null` if no unicorn element can be found before the root.
205+
*/
206+
getUnicornParent() {
207+
// const parentEl = this.el.parentElement;
208+
let parentElement = this.parent;
209+
210+
while (!parentElement.isUnicorn) {
211+
if (parentElement.el.getAttribute("unicorn:checksum")) {
212+
return null;
213+
}
214+
215+
parentElement = parentElement.parent;
216+
}
217+
218+
return parentElement;
219+
}
220+
201221
/**
202222
* Check if another `Element` is the same as this `Element`.
203223
* @param {Element} other

django_unicorn/static/js/eventListeners.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,12 @@ import { Element } from "./element.js";
1717
*/
1818
export function addActionEventListener(component, eventType) {
1919
component.document.addEventListener(eventType, (event) => {
20-
const targetElement = new Element(event.target);
20+
let targetElement = new Element(event.target);
21+
22+
// Make sure that the target element is a unicorn element.
23+
if (targetElement && !targetElement.isUnicorn) {
24+
targetElement = targetElement.getUnicornParent();
25+
}
2126

2227
if (
2328
targetElement &&

tests/js/element/action.test.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,23 @@ test("multiple actions", (t) => {
5050
t.true(element.actions[1].eventType === "keydown");
5151
});
5252

53-
test("$event action variable invaid property", (t) => {
53+
test("click on internal element", (t) => {
54+
const html = `
55+
<div unicorn:id="5jypjiyb" unicorn:name="text-inputs" unicorn:checksum="GXzew3Km">
56+
<input unicorn:model='name'></input>
57+
<button unicorn:click='test()'><span id="clicker">Click</span></button>
58+
</div>`;
59+
const component = getComponent(html);
60+
61+
t.is(component.attachedEventTypes.length, 1);
62+
t.is(component.actionEvents.click.length, 1);
63+
64+
component.actionEvents.click[0].element.el.children[0].click();
65+
66+
t.is(component.actionQueue.length, 1);
67+
});
68+
69+
test("$event action variable invalid property", (t) => {
5470
const html = `
5571
<div unicorn:id="5jypjiyb" unicorn:name="text-inputs" unicorn:checksum="GXzew3Km">
5672
<input unicorn:model='name'></input>

0 commit comments

Comments
 (0)