-
-
Notifications
You must be signed in to change notification settings - Fork 391
Expand file tree
/
Copy pathstimulus.ts
More file actions
45 lines (33 loc) · 1.09 KB
/
stimulus.ts
File metadata and controls
45 lines (33 loc) · 1.09 KB
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
import type {Context, Controller} from "@hotwired/stimulus";
import {Application} from "@hotwired/stimulus";
import {assert} from "helpers/assert";
let application: Application | null = null;
type ControllerClass<T> = new (context: Context) => T;
async function bootStimulus<T extends Controller>(
name: string,
controller: ControllerClass<T>,
): Promise<void> {
application ??= Application.start();
application.register(name, controller);
application.handleError = (error: Error): void => { throw error; };
await Promise.resolve();
}
function getController<T extends Controller>(
element: HTMLElement,
name: string,
controllerClass: ControllerClass<T>,
): T {
const controller =
assert(application).getControllerForElementAndIdentifier(element, name);
if (controller instanceof controllerClass) {
return controller;
} else if (controller) {
throw new Error("Controller class does not match");
}
throw new Error("Controller not found");
}
afterEach(() => {
if (application) { application.stop(); }
application = null;
});
export {bootStimulus, getController};