2

I want to be able to pass custom data to a simulated JavaScript event so that I can uniquely identify this simulated event in an event listener callback. For example, if I were to call:

var event = document.createEvent("MouseEvents");
var args = ['mousemove', true, true, window, 1, 0, 0];
event.initMouseEvent.apply(event, args);
target.dispatchEvent(event);

How would I be able to pass data to this event and then retrieve it from an event listener callback?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Justin Meltzer
  • 13,318
  • 32
  • 117
  • 182

1 Answers1

5

Just add that data to your event object should be enough:

target.addEventListener("mousemove", function(e) {
    console.log(e.data);
}, false);

var event = document.createEvent("MouseEvents");
var args = ['mousemove', true, true, window, 1, 0, 0];
event.data = "foobar";
event.initMouseEvent.apply(event, args);
target.dispatchEvent(event);

P.S. Notice that the args are not enough in some browsers, all of them are required otherwise an exception is thrown. I'm not sure what are the browsers you want to supports. For all the arguments, see: https://developer.mozilla.org/en/docs/DOM/event.initMouseEvent

ZER0
  • 24,846
  • 5
  • 51
  • 54
  • I'm not sure about all browsers supporting custom data in the mouse event. – Mohammad Haseeb Feb 10 '13 at 23:32
  • Yeah this is what I'm looking for, but I'm curious as to @mhaqs point as well. I can't use my own custom events though - it needs to be a "mousemove" event. – Justin Meltzer Feb 10 '13 at 23:32
  • I'm not sure about IE because I'm not a Windows user, and IE has always unpredictable behaviors. However, this is not about supporting custom data in mouse event, it's just add dynamic property to a javascript object that is definitely widely supported (and event object are not an exception). – ZER0 Feb 10 '13 at 23:36
  • Just look here, http://stackoverflow.com/questions/9417121/is-there-any-way-of-passing-additional-data-via-custom-events. Tagging this as duplicate question. – Mohammad Haseeb Feb 10 '13 at 23:42
  • 3
    It's not a duplicate. `CustomEvent` are made to have custom data, see: https://developer.mozilla.org/en-US/docs/DOM/Event/CustomEvent, the `any` parameter. The OP doesn't want to have a `CustomEvent`, but a `MouseEvent` with custom data. It's different. – ZER0 Feb 10 '13 at 23:45