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?
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