I'm creating a custom event in plain Javascript and attaching it to a DOM element. The element has multiple event listeners for the same event. The code I've written is:
var element = document.getElementById('demo');
element.addEventListener("myCustomEvent", function(e) {
console.log("myCustomEvent first handler triggered");
});
element.addEventListener("myCustomEvent", function(e) {
console.log("myCustomEvent second handler triggered");
e.data['otherKey'] = 'other value';
return e.data;
});
// Trigger the event
var event = new CustomEvent("myCustomEvent", {
data: {
firstKey: 'first Value'
}
});
element.dispatchEvent(event);
Now what I want is, get the data from last event handler like below:
var modifiedData = element.dispatchEvent(event);
Though I know the above line may not be correct, but I want something like that. If I use jQuery, there is pretty simple thing like $.triggerHandler I can use that iterates over all the listeners for a particular event and gives the return value of last handler if any.
But I want to do it in pure Javascript. Is there any solution for such kind of thing?