Skip to content

Commit 929cdeb

Browse files
feat: custom evens
1 parent e978fe9 commit 929cdeb

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/events/event.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { Actions, EventData } from './types';
2+
3+
const namespace = 'nmr-wrapper';
4+
5+
function trigger<T extends Actions>(action: T, data: EventData<T>) {
6+
const event = new CustomEvent(`${namespace}:${action}`, {
7+
detail: data,
8+
});
9+
window.dispatchEvent(event);
10+
}
11+
12+
function on<T extends Actions>(
13+
action: T,
14+
dataListener: (data: EventData<T>, event?: Event) => void,
15+
options?: boolean | AddEventListenerOptions,
16+
) {
17+
function listener(object: Event) {
18+
const { detail, ...event } = object as CustomEvent;
19+
dataListener?.(detail, event);
20+
}
21+
window.addEventListener(`${namespace}:${action}`, listener, options);
22+
}
23+
24+
function clean(action: Actions, listener: (object: Event) => void) {
25+
window.removeEventListener(`${namespace}:${action}`, listener);
26+
}
27+
28+
export default { trigger, on, clean };

src/events/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { Actions } from './types';
2+
import event from './event';
3+
4+
export default event;
5+
export type { Actions };

src/events/types.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
type Actions = 'load' | 'test';
2+
3+
interface LoadSpectra {
4+
urls: string[];
5+
}
6+
interface TestData {
7+
testData: string;
8+
}
9+
10+
type EventData<T extends Actions> = T extends 'load'
11+
? LoadSpectra
12+
: T extends 'test'
13+
? TestData
14+
: never;
15+
export type { Actions, EventData };

0 commit comments

Comments
 (0)