'Javascript dispatchEvent - How to change eventArgs

I have a custom event that is fired by a certain function.

This event contains an eventArgs with detail and so. I wish that the handlers/listeners be able to change the eventArgs so the original function gets its changed value. Is that possible?

So far I've tried this:

Handler/Listener

document.addEventListener('myCustomEvent', function(eventArgs)
{
    eventArgs.detail.value = newValue; // I want the listener to change the value in "e"
});
        

Caller

var eventArgs = {                   
    detail:         
    {               
        value: originalValue;
    },              
    bubbles: false, //not sure what this does
    cancelable: false, //not sure what this does
};
                                     
document.dispatchEvent(new CustomEvent('myCustomEvent', eventArgs ));   

//do things here with a changed eventArgs after the event is fired

The change made in the listener does not reach the caller. I tried also to add complex objects inside eventArgs.detail, but in that case, the handler gets a null eventArgs.

Is it impossible to accomplish or am I missing something?


Important: I'm doing that in a Chrome extension, where the event is fired in a script directly attached to the document, and the listener belongs to the extension code (content script).



Solution 1:[1]

That should work, keep in mind you have to call addEventListener, BEFORE the call to dispatchEvent. Javascript passes objects by reference so any mutations are done on the original object.

var eventArgs = {
    detail: {
        value: 5
    }
};

document.addEventListener('myCustomEvent', function(eventArgs)
{
    eventArgs.detail.value = 6; // I want the listener to change the value in "e"
});
document.dispatchEvent(new CustomEvent('myCustomEvent', eventArgs));

$('#button').click(function() {
    alert(eventArgs.detail.value);
});

https://jsfiddle.net/polarisjunior/uLwaw924/1/ If you click the button you can see the value is updated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PJ K