How do I create a custom event class similar to ActionScript? What I mean by that is a class that I can use to fire off my own events, send the necessary data.
I don't want to use third-party libraries like YUI or jQuery to do it. My goal is to be able to send a event that looks like this:
document.addEventListener("customEvent", eventHandler, false); function eventHandler(e){ alert(e.para1); } document.dispatchEvent(new CustomEvent("customEvent", para1, para2));
Please no third-party library solutions.
The custom events allow you to decouple the code that you want to execute after another piece of code completes. For example, you can separate the event listeners in a separate script. In addition, you can have multiple event listeners to the same custom event.
A method that worked for me was to call document.createEvent(), init it and dispatch it with window.dispatchEvent().
var event = document.createEvent("Event"); event.initEvent("customEvent", true, true); event.customData = getYourCustomData(); window.dispatchEvent(event);
I'm a little late to the party here, but was searching for the same thing. I'm not keen on the first answer (above) because it relies upon the document to manage the custom event. This is dangerous because it's global and could potentially conflict with another script should that script coincidentally rely on the same custom event.
The best solution I've found is here: Nicholas C. Zakas - Custom Events in Javascript
Unfortunately, since javascript doesn't support inheritance keywords, it's a bit messy with prototyping, but it definitely keeps things tidy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With