-
Notifications
You must be signed in to change notification settings - Fork 3
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
2 changed files
with
51 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"name": "@jlarky/rad-event-listener", | ||
"version": "0.2.4", | ||
"exports": "./mod.ts" | ||
} |
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 |
---|---|---|
@@ -0,0 +1,46 @@ | ||
export function radEventListener< | ||
MyElement extends { addEventListener: any; removeEventListener: any }, | ||
// get the possible events by using the `MyElement.on${someEvent}` properties | ||
Event extends { | ||
[K in keyof MyElement]-?: K extends `on${infer E}` ? E : never; | ||
}[keyof MyElement] | ||
>( | ||
element: MyElement, | ||
// recreate the args for addEventListener | ||
...args: [ | ||
type: Event, | ||
// grab the correct types off the function | ||
listener: MyElement extends Record< | ||
`on${Event}`, | ||
null | ((...args: infer Args) => infer Return) | ||
> | ||
? // overwrite the type of this to make sure that it is always `MyElement` | ||
(this: MyElement, ...args: Args) => Return | ||
: never, | ||
options?: boolean | AddEventListenerOptions | ||
] | ||
): () => void { | ||
element.addEventListener(...args); | ||
return () => { | ||
element.removeEventListener(...args); | ||
}; | ||
} | ||
|
||
export { radEventListener as on }; | ||
|
||
export function rad< | ||
MyElement extends { addEventListener?: any; removeEventListener?: any } | ||
>( | ||
element: MyElement, | ||
gen: (rad: MyElement["addEventListener"]) => void | ||
): () => void { | ||
let cleanup: undefined | (() => void); | ||
gen((listener: any, options: any) => { | ||
element.addEventListener(listener, options); | ||
cleanup = () => element.removeEventListener(listener, options); | ||
}); | ||
if (!cleanup) { | ||
throw new Error("you forgot to add event listener"); | ||
} | ||
return cleanup; | ||
} |