Created
June 12, 2023 15:00
-
-
Save ahmu83/2d16cc583e71acdcf08225ba90dda089 to your computer and use it in GitHub Desktop.
Dispatch an event using CustomEvent constructor, that can be listened to using addEventListener method
This file contains hidden or 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
/** | |
* Dispatch an event using CustomEvent constructor, | |
* that can be listened to using addEventListener method | |
* | |
* Example usage: | |
* | |
* dispatchAnEvent('my-custom-event', {data: 'The data'}) | |
* | |
* window.addEventListener('my-custom-event', function(event) { | |
* | |
* var data = event.detail.data; | |
* | |
* console.log('data', data); | |
* | |
* }); | |
* | |
* @param string eventName Name of the event | |
* @param object detail Data to send in the event | |
* @param object element Element object to attach the event to | |
* @return void | |
*/ | |
function dispatchAnEvent(eventName, detail = {}, element = document) { | |
var CustomEventObject = new CustomEvent(eventName, { | |
'detail': detail, | |
}); | |
element.dispatchEvent(CustomEventObject); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment