-
Notifications
You must be signed in to change notification settings - Fork 0
/
phoenix_webcomponent.js
41 lines (39 loc) · 1.63 KB
/
phoenix_webcomponent.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import '@gsmlg/lit';
export const PhxWCHook = {
mounted() {
const attrs = this.el.attributes;
const phxTarget = attrs["phx-target"].value;
const pushEvent = phxTarget
? (event, payload, callback) =>
this.pushEventTo(phxTarget, event, payload, callback)
: this.pushEvent;
for (var i = 0; i < attrs.length; i++) {
if (/^phx-wc-send-/.test(attrs[i].name)) {
const eventName = attrs[i].name.replace(/^phx-wc-send-/, "");
const [phxEvent, callbackName] = attrs[i].value.split(';');
this.el.addEventListener(eventName, ({ detail }) => {
pushEvent(phxEvent, detail, (e) => {
this[callbackName]?.(e, detail, eventName)
});
});
}
if (/^phx-wc-receive-/.test(attrs[i].name)) {
const eventName = attrs[i].name.replace(/^phx-wc-receive-/, "");
const handler = attrs[i].value;
this.handleEvent(eventName, (payload) => {
if (handler && this.el[handler]) {
this.el[handler]?.(payload);
} else {
this.el.dispatchEvent(new CustomEvent(eventName, { detail: payload }));
}
});
}
if ('phx-wc-receive' === attrs[i].name) {
const [phxEvent, callbackName] = attrs[i].value.split(';');
this.handleEvent(phxEvent, (payload) => {
this.el[callbackName]?.(payload);
});
}
}
},
};