/
define.js
51 lines (41 loc) · 1.36 KB
/
define.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
42
43
44
45
46
47
48
49
50
51
/* global bindAttributes, bindEventListeners, createShadowRoot, findReferences */
export default function define(CustomElement) {
const elementName = CustomElement
?.name
?.replace(/([a-z])([A-Z])/g, '$1-$2')
?.toLowerCase();
customElements.define(elementName, class extends CustomElement {
constructor() {
super();
const { template, data } = this;
const { settings = {} } = this.constructor;
const $target = template ? createShadowRoot(this, template, settings?.createShadowRoot) : this;
this.$refs = findReferences($target, settings?.findReferences);
this.data = data ? bindAttributes($target, data, settings?.bindAttributes) : data;
bindEventListeners($target, this, settings?.bindEventListeners);
this.ready?.($target);
}
dispatchEvent(name, detail, settings = {}) {
const defaults = {
bubbles: true,
composed: false,
cancelable: false,
};
super.dispatchEvent(
new CustomEvent(name, {
...defaults,
...settings,
detail,
}),
);
}
});
}
define.async = async (name, settings = {}) => {
const defaults = {
key: 'default',
path: import.meta?.url?.replace(/\/([^/]+\.m?js)?$/, '') ?? '.',
};
const { key, path } = { ...defaults, ...settings };
define((await import(`${path}/${name}`))[key]);
};