Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a custom event class in Javascript?

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.

like image 922
Josua Pedersen Avatar asked Jan 13 '10 19:01

Josua Pedersen


People also ask

What is the use of a custom event?

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.


2 Answers

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); 
like image 76
pfleidi Avatar answered Oct 14 '22 07:10

pfleidi


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.

like image 39
Rich Hauck Avatar answered Oct 14 '22 05:10

Rich Hauck