Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Event creation with customly attached data

Is there a JavaScript way to pass custom data to a manually created JavaScript event?

Ok, let's say I got this code to create and trigger a JavaScript event:

var evObj = document.createEvent('HTMLEvents');
evObj.initEvent('submit', bubbling, cancelable);
anElement.dispatchEvent(evObj);

This works fine and can be handled by using this code:

document.addEventListener('submit', mySubmitEventHandler, true);

But, I need a way to pass additional data to the event, so that mySubmitEventHandler knows whether the event was fired by a user or by JavaScript event creation as shown above. A boolean value would be sufficient.

So, how can I add something like "myEvent = true" to the newly created evObj?

And please no jQuery answers, I need to do this one in pure JavaScript.

like image 216
Alp Avatar asked Jan 30 '12 22:01

Alp


People also ask

How can you create a custom synthetic event?

A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.

What is JavaScript CustomEvent?

Adding custom data – CustomEvent()To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows: const event = new CustomEvent('build', { detail: elem.


2 Answers

Attach the parameter to evObj.

evObj.flag = 'Hi!';
anElement.dispatchEvent(evObj);

This code demonstrates that the event object passed by dispatchEvent is equal to the one in the event listener (Live demo):

var evObj = document.createEvent('HTMLEvents');
document.body.addEventListener('test', function(e){ alert(e === evObj); },true);
evObj.initEvent('test', true, true);
document.body.dispatchEvent(evObj); // Shows alert, "true"
like image 164
Rob W Avatar answered Oct 05 '22 16:10

Rob W


your evObj it's a normal object you can add any data as a property of the object like evObj.myData = "blablabla"; and then read the data in the listener

Hope this helps

like image 36
wezzy Avatar answered Oct 05 '22 16:10

wezzy