Having problems with emitted event between controllers

I have two controllers registered in my Application

a Dropzone element, running as polaris-dropzone controller

application.register("polaris-dropzone", Dropzone);

and a home controller for my homepage, that renders the polaris-dropzone element.

application.register("home", HomeController)

The Dropzone Controller emits an event with this code:

const dropEvent = new CustomEvent("polaris-dropzone:drop", {
  detail: {
    files: this.files,
    acceptedFiles: this.acceptedFiles,
    rejectedFiles: this.rejectedFiles
  }
});
this.element.dispatchEvent(dropEvent);

I listen for that event in my home controller by wiring up a connection:

<div data-controller="home polaris-dropzone" data-action="polaris-dropzone:drop->home#drop">

I expected my homeController drop method to receive the details from this event that occurred in the Dropzone controller! I never get anything in my homeController drop method when that event does indeed fire off in the Dropzone controller. Silence. Nada.

I seems so easy. But it is not. What am I missing here? What am I doing wrong?

It looks like that should work. I wonder if the drop event is being caught further up in the DOM? Have you tried listening for the event at the document level to catch the event as it bubbles up?

Make sure bubbling is enabled in your custom event:

const dropEvent = new CustomEvent("polaris-dropzone:drop", {
  bubbles: true,
  detail: {...}
});
this.element.dispatchEvent(dropEvent);

And then listen for the event at the document level:

<div data-controller="home polaris-dropzone" data-action="polaris-dropzone:drop@document->home#drop">
1 Like

That was it. I had to add the bubbles: true to the event and it was indeed caught.

Thank you.

1 Like

that’s weird because I’v used custom events a bit and never had to add bubbles: true, but could be because I dispatch it from window content ? dunno …

    const custom_event = new CustomEvent(event_name, { detail: event_detail })
    window.dispatchEvent(custom_event)

What’s more stimulus way ? :slight_smile: