Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript CustomEvent detail not getting passed

I am trying to create a custom Javascript event. The event works and fires correctly, but the 'detail' object that I'm passing it is not available.

Here's the code I'm using to create and dispatch the event:

var double_tap = new CustomEvent("doubleTap", {
    detail: {
        hello: 'world'  
    },
    bubbles: true,
    cancelable: true
});

this.dispatchEvent(double_tap);

Then I'm using jQuery to add an event listener to the body:

$('body').on('doubleTap', function( e ) { 
    console.log(e);
});

It does fire, and the console log happens, but unfortunately the log only outputs the event details including bubbles and cancelable properties, but never the 'detail' object, so that information is not accessible.

Here's a jsbin as example, I'm creating the event on the click event of the body so you can see the console; http://jsbin.com/looseroots/6

I would like to be able to get the data from the 'detail' object when the event is fired. What am I doing wrong? I have tested this in Chrome, and Safari on iOS.

like image 878
Joel Avatar asked Nov 11 '12 17:11

Joel


People also ask

How to create a custom event in JavaScript?

To create a custom event, you use the CustomEvent () constructor: let event = new CustomEvent (eventType, options); Code language: JavaScript (javascript) The CustomEvent () has two parameters:

How do you dispatch a custom event in JavaScript?

You can dispatch custom events like so: To listen for the custom event, add an event listener to the element you want to listen on, just as you would with native DOM events. How do JavaScript custom events work?

What are the parameters of a customevent?

The CustomEvent () has two parameters: The eventType is a string that represents the name of the event. The options is an object has the detail property that contains any custom information about the event. The following example shows how to create a new custom event called highlight:

Can we assign handlers to events from JavaScript?

We can not only assign handlers, but also generate events from JavaScript. Custom events can be used to create “graphical components”. For instance, a root element of our own JS-based menu may trigger events telling what happens with the menu: open (menu open), select (an item is selected) and so on.


2 Answers

obj.addEventListener("eventName", function(e) {
console.log(e.your_property)
})

var event = new CustomEvent("eventName");
event.your_property = { key: "value" };

obj.dispatchEvent(event);

You can create properties in your CustomEvent, when you dispatch you are sending it.

like image 80
ezequiel Avatar answered Oct 07 '22 14:10

ezequiel


You need to access the originalEvent property for the details

console.log(e.originalEvent.detail);
like image 14
lostsource Avatar answered Oct 07 '22 14:10

lostsource