-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.mjs
43 lines (37 loc) · 1.18 KB
/
index.mjs
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
42
const EventHandlerMixin = (superclass) => class extends superclass {
constructor() {
super()
this.eventsToRemove = []
}
connectedCallback() {
const htmlElementPrototype = Object.getOwnPropertyNames(HTMLElement.prototype)
const attrs = this?.state?.attrs
Object.keys(attrs)
.map(event => {
if (htmlElementPrototype.indexOf(`on${event}`) !== -1) {
const target = attrs[event]
? this.querySelector(attrs[event]) ||
this.shadowRoot.querySelector(attrs[event]) ||
this
: this
if (target && this[event]) {
target.addEventListener(event, this[event].bind(this))
this.eventsToRemove.push({ target, event: this[event] })
}
else {
throw Error(`Unable to add event listener. Double check ${event}="${attrs[event]}".`)
}
}
})
if(super.connectedCallback) {
super.connectedCallback()
}
}
disconnectedCallback() {
this.eventsToRemove.forEach(l => removeEventListener(l.event, l.target))
if (super.disconnectedCallback) {
super.disconnectedCallback()
}
}
}
export default EventHandlerMixin