How do I create a custom event class in Javascript?

24,590

Solution 1

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);

Solution 2

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.

Solution 3

This is straightforward when using DOM elements to broker the events.

Given an element:

var element = document.querySelector('div#rocket');

For a client to subscribe:

element.addEventListener('liftoff', function(e)
{
    console.log('We have liftoff!');
});

Then to dispatch/raise/fire the event, use this code:

element.dispatch(new Event('liftoff'));
Share:
24,590
Josua Pedersen
Author by

Josua Pedersen

Updated on October 24, 2021

Comments

  • Josua Pedersen
    Josua Pedersen over 2 years

    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.