Skip to content

Instantly share code, notes, and snippets.

@pgarciacamou
Last active September 11, 2015 20:43
Show Gist options
  • Save pgarciacamou/b673baf4efde27b24199 to your computer and use it in GitHub Desktop.
Save pgarciacamou/b673baf4efde27b24199 to your computer and use it in GitHub Desktop.
Custom Events
// Object that implements the Event Handler Interface
var a = {
handleEvent: function (e){
console.log('hola', e.detail);
}
};
// Custom Event
var custom = new Event('myevent');
// To add custom data, we can use:
var evt = new CustomEvent('myevent', { detail: {
prop: 'value'
}});
// Example of how to subscribe to custom event
// No matter how many times you add the same event
// it will only add it once
document.body.addEventListener('myevent', a, false);
document.body.addEventListener('myevent', a, false);
document.body.addEventListener('myevent', a, false);
// To dispatch the custom event
document.body.dispatchEvent(evt);
// Remove Event Listener
// You need to send the instance
document.body.removeEventListener('myevent', a);
function _dispatchEvent(element, eventName, eventData) {
var ev = document.createEvent("Event");
ev.data = eventData;
ev.initEvent(eventName, true, true);
element.dispatchEvent(ev);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment