Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good example of using event constructors in js?

I am trying to figure out how to properly create and fire events in JavaScript, so in the process of learning ran into this page:

https://developer.mozilla.org/en-US/docs/DOM/document.createEvent

Which at the top informs me of the following:

The createEvent method is deprecated. Use event constructors instead.

Googling JS event constructors was not very fruitful - topics talking about constructors in general, but not what I am looking for. Could somebody please explain to me what are the event constructors and provide a good example of their usage?

like image 451
NindzAI Avatar asked Apr 11 '13 14:04

NindzAI


1 Answers

From https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent:

It seems that events are now encapsulated in a class called CustomEvent. You can think of the old document.createEvent as a factory method that returns an event object. Now, instead of using document.createEvent to create the object, you now have access to create the object directly.

    //this is the new way
    var my_event = new CustomEvent('NewEventName');
    var my_element = document.getElementById('TargetElement');
    my_element.dispatchEvent(my_event);

is the replacement for

    //this is the old way
    var my_event = document.createEvent('NewEventName');
    var my_element = document.getElementById('TargetElement');
    my_element.dispatchEvent(my_event);
like image 74
Kaz Higaki Avatar answered Sep 28 '22 10:09

Kaz Higaki