问题
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, im 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
回答1:
You need to access the originalEvent property for the details
console.log(e.originalEvent.detail);
回答2:
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.
回答3:
I found the following commit: https://github.com/jquery/jquery/commit/a90ff8c8c79bfcc32afd340a12f016f20a31d8b6
This fix is in jQuery's compat
branch and should be fixed as of jQuery 3.0.
来源:https://stackoverflow.com/questions/13333683/javascript-customevent-detail-not-getting-passed