Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create proper DOM events from string #133

Open
fregante opened this issue Dec 8, 2021 · 2 comments
Open

Create proper DOM events from string #133

fregante opened this issue Dec 8, 2021 · 2 comments

Comments

@fregante
Copy link

fregante commented Dec 8, 2021

When creating events, you should use the right constructor. For example new MouseEvent('click') instead of a plain new Event('click').

As far as I know there's no way to this automatically so there could be DOM event creator that includes such map.

import createEvent from '✨';

document.body.dispatchEvent(createEvent('keydown', {key: 'a'}))

This particularly useful when your app can trigger a variety of events and you can't be bothered to match them manually 😃

import createEvent from '✨';

const eventsToDispatch = ['mousedown', 'pointerdown', 'click', 'mouseup', 'pointerup']
for (const eventName of eventsToDispatch)
	document.body.dispatchEvent(createEvent(eventName))
@Richienb
Copy link

Richienb commented Dec 9, 2021

I was able to compile a list of dom events but I ran into a bit of trouble when writing the TypeScript definition since the event name needs to be detected to determine the return value.

@fregante
Copy link
Author

fregante commented Dec 9, 2021

It's not super easy, but you can use generics to maintain the mapping. Something like:

const events = {
	click: MouseEvent
} as const;
type Events = typeof events;
function createEvent<Name extends keyof Events >(name: Name): Events[Name] {
//
}

What's missing from here:

  • allowing unknown events
  • mapping unknown events to CustomEvent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants