Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created July 5, 2023 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/ec155434954561654a9e3351bc6d6a3f to your computer and use it in GitHub Desktop.
Save cferdinandi/ec155434954561654a9e3351bc6d6a3f to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>emit</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
/**
* Emit a custom event
* (c) Chris Ferdinandi, MIT License, https://gomakethings.com
* @param {String} type The event type
* @param {Object} detail Any details to pass along with the event
* @param {Node} elem The element to attach the event to
*/
function emit (type, detail = {}, elem = document) {
// Make sure there's an event type
if (!type) return;
// Create a new event
let event = new CustomEvent(type, {
bubbles: true,
cancelable: true,
detail: detail
});
// Dispatch the event
return elem.dispatchEvent(event);
}
window.addEventListener('my-library:custom-event', function (event) {
console.log(event.detail);
}, false);
emit('my-library:custom-event', {
greeting: 'Hello, world!'
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment