-
Notifications
You must be signed in to change notification settings - Fork 0
/
component.ts
55 lines (43 loc) · 1.68 KB
/
component.ts
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
52
53
54
55
// eslint-disable-next-line @typescript-eslint/no-triple-slash-reference,spaced-comment
/// <reference types="jquery" />
/*
* This is a component that you can extend from to avoid copy-pasting the jquery way of making it
* available on handlebars.
*/
type DataType = string | number | boolean | object;
let isNumeric: (value: DataType) => boolean;
export abstract class Component {
protected static globalName: string;
protected element: HTMLElement;
public constructor(element: HTMLElement) {
this.element = element;
}
public static register(jquery: JQueryStatic): void {
const childClass = this;
isNumeric = isNumeric || jquery.isNumeric;
if (!childClass.globalName) {
throw new Error('You did not set the "globalName" variable on your component.');
}
// eslint-disable-next-line no-param-reassign,func-names,@typescript-eslint/no-explicit-any
jquery.fn[childClass.globalName] = function (...args: any[]) {
const element = this as JQuery;
if (!element.data(childClass.globalName) && element.length) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
element.data(childClass.globalName, new (childClass as any)(element[0], ...args));
}
};
}
protected getDataAttr(atributeName: string): DataType {
const attribute: Attr | null = this.element.attributes.getNamedItem(`data-${atributeName}`);
let parsedValue: DataType = attribute ? attribute.value : undefined;
if (isNumeric(parsedValue)) {
parsedValue = +(parsedValue);
} else {
try {
parsedValue = JSON.parse(parsedValue);
// eslint-disable-next-line no-empty
} catch (_) {}
}
return parsedValue;
}
}