Last active
September 11, 2015 20:43
-
-
Save pgarciacamou/b673baf4efde27b24199 to your computer and use it in GitHub Desktop.
Custom Events
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
// 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); |
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
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