Type safe listener for custom/native events and dispatcher for custom events
import { listenEvent } from '@ribeirolabs/events';
// adds event listener
const unlisten = listenEvent('hashchange', (e) => console.log(e.name));
// removes event listener
unlisten();
You can also use it to unlisten a specific event.
import { unlistenEvent } from '@ribeirolabs/events';
// removes event listener
unlistenEvent('hashchange');
import { listenEvent, dispatchCustomEvent } from '@ribeirolabs/events';
listenEvent('my-event', (event) => {
console.log(event.detail.message); // it works
});
dispatchCustomEvent('my-event', {
message: 'it works',
});
This hook automatically adds the listener on mount and removes it on unmount.
import { useEvent } from '@ribeirolabs/events/react';
function Component() {
const listener = useCallback((event) => {
console.log(event.name);
}, []);
useEvent('hashchange', listener);
}
It adds a global ribeirolabs.events
with all the methods.
<script src="https://unpkg.com/@ribeirolabs/events/index.browser.js"></script>
<script>
ribeirolabs.events.listenEvent('my-event', (event) => {
console.log(event.detail.message) // it works!
});
ribeirolabs.events.dispatchCustomEvent('my-event', {
message: 'it works!',
});
ribeirolabs.events.unlistenEvent();
</script>
To work with modules.
<script type="module">
import { listenEvent, dispatchCustomEvent, unlistenEvent } from "https://unpkg.com/@ribeirolabs/events/index.mjs";
listenEvent('my-event', (event) => {
console.log(event.detail.message) // it works!
});
dispatchCustomEvent('my-event', {
message: 'it works!',
});
unlistenEvent();
</script>
You can type your custom events, just declare a global Events
interface. We
suggest that you create an events.d.ts
file inside the root folder.
interface Events {
'my-event': {
message: string;
};
};
Now dispatchCustomEvent
will be typed based on that interface, and the other
methods will also consider these events.