I'm trying to incorporate a CustomEvent in my workflow. But I need this event to be a communication in both ways: a script sends the event to the document, and it should respond to the same initiator.
I've tried stuff along the lines of:
ev = new CustomEvent('StorageRequest', {
detail: {
space: theSpace,
method: theMethod,
arguments: args
}
})
document.dispatchEvent(ev)
And my listener looks like this:
document.addEventListener('StorageRequest', (e) => {
console.debug('Sending StorageRequest', e)
// do something, then answer back with response
})
What's the way to achieve this?
I've tried using a Promise and sending the response using resolve/reject, but passing functions seems to break the detail in the event and it turns out to be null if I try to do that:
return new Promise((resolve, reject) => {
ev = new CustomEvent('StorageRequest', {
detail: {
space: theSpace,
method: theMethod,
arguments: args,
resolve, reject
}
})
document.dispatchEvent(ev)
})
Notes: I'd like to avoid "generically" sending the response back to the document. I prefer the requests and responses to be fully intentional and handled within the code properly
I don't have an element attached to this, so using the element frome.targetisn't an option (unless I can do something else with it)