/
context.ts
93 lines (76 loc) · 2.35 KB
/
context.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Action } from "./action"
import { ActionObserver, ActionObserverDelegate } from "./action_observer"
import { Application } from "./application"
import { Controller } from "./controller"
import { ErrorHandler } from "./error_handler"
import { EventListenerSet } from "./event_listener_set"
import { Module } from "./module"
import { Schema } from "./schema"
import { Scope } from "./scope"
export class Context implements ErrorHandler, ActionObserverDelegate {
readonly module: Module
readonly scope: Scope
readonly controller: Controller
private actionObserver: ActionObserver
private eventListeners: EventListenerSet
constructor(module: Module, scope: Scope) {
this.module = module
this.scope = scope
this.actionObserver = new ActionObserver(this.element, this.schema, this)
this.eventListeners = new EventListenerSet(this)
try {
this.controller = new module.controllerConstructor(this)
this.controller.initialize()
} catch (error) {
this.handleError(error, "initializing controller")
}
}
connect() {
this.actionObserver.start()
this.eventListeners.start()
try {
this.controller.connect()
} catch (error) {
this.handleError(error, "connecting controller")
}
}
disconnect() {
try {
this.controller.disconnect()
} catch (error) {
this.handleError(error, "disconnecting controller")
}
this.eventListeners.stop()
this.actionObserver.stop()
}
get application(): Application {
return this.module.application
}
get identifier(): string {
return this.module.identifier
}
get schema(): Schema {
return this.application.schema
}
get element(): Element {
return this.scope.element
}
get parentElement(): Element | null {
return this.element.parentElement
}
// Inline action observer delegate
/** @private */
actionConnected(action: Action) {
this.eventListeners.addEventListenerForAction(action)
}
/** @private */
actionDisconnected(action: Action) {
this.eventListeners.deleteEventListenerForAction(action)
}
// Error handling
handleError(error: Error, message: string, detail: object = {}) {
const { identifier, controller, element } = this
detail = Object.assign({ identifier, controller, element }, detail)
this.application.handleError(error, `Error ${message}`, detail)
}
}