/
controller.ts
78 lines (61 loc) · 1.86 KB
/
controller.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Application } from "./application"
import { ClassPropertiesBlessing } from "./class_properties"
import { Constructor } from "./constructor"
import { Context } from "./context"
import { TargetPropertiesBlessing } from "./target_properties"
import { ValuePropertiesBlessing, ValueDefinitionMap } from "./value_properties"
export type ControllerConstructor = Constructor<Controller>
export class Controller<ElementType extends Element = Element> {
static blessings = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing]
static targets: string[] = []
static values: ValueDefinitionMap = {}
static get shouldLoad() {
return true
}
static afterLoad(_identifier: string, _application: Application) {
return
}
readonly context: Context
constructor(context: Context) {
this.context = context
}
get application() {
return this.context.application
}
get scope() {
return this.context.scope
}
get element() {
return this.scope.element as ElementType
}
get identifier() {
return this.scope.identifier
}
get targets() {
return this.scope.targets
}
get classes() {
return this.scope.classes
}
get data() {
return this.scope.data
}
initialize() {
// Override in your subclass to set up initial controller state
}
connect() {
// Override in your subclass to respond when the controller is connected to the DOM
}
disconnect() {
// Override in your subclass to respond when the controller is disconnected from the DOM
}
dispatch(
eventName: string,
{ target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true } = {}
) {
const type = prefix ? `${prefix}:${eventName}` : eventName
const event = new CustomEvent(type, { detail, bubbles, cancelable })
target.dispatchEvent(event)
return event
}
}