-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
47 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,23 @@ | ||
export function dispatch(eventName: string) { | ||
const event = new Event(eventName); | ||
export function dispatch<T>(eventName: string, detail?: T) { | ||
const event = new CustomEvent(eventName, { detail }); | ||
|
||
document.dispatchEvent(event); | ||
} | ||
|
||
export function subscribe(eventName: string, listener: () => void) { | ||
document.addEventListener(eventName, listener); | ||
export function subscribe<T>(eventName: string, listener: (e: T) => void) { | ||
const handler = (event: Event) => { | ||
if ('detail' in event) { | ||
const payload = event.detail as T; | ||
|
||
listener(payload); | ||
} | ||
}; | ||
|
||
document.addEventListener(eventName, handler); | ||
|
||
return () => unsubscribe(eventName, handler); | ||
} | ||
|
||
export function unsubscribe(eventName: string, listener: () => void) { | ||
export function unsubscribe(eventName: string, listener: (e: Event) => void) { | ||
document.removeEventListener(eventName, listener); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,11 @@ | ||
import { dispatch, subscribe, unsubscribe } from './event'; | ||
import { dispatch, subscribe } from './event'; | ||
|
||
export function closeModals() { | ||
dispatch('closeModals'); | ||
} | ||
|
||
export function onCloseModals(listener: () => void) { | ||
subscribe('closeModals', listener); | ||
const unsubscribe = subscribe('closeModals', listener); | ||
|
||
return () => unsubscribe('closeModals', listener); | ||
return unsubscribe; | ||
} |