Event firing on controller disconnect

Just wondering if anyone else had come across the problem of firing events from a controller’s disconnect method?

I have a nested form where the parent controller needs to know when child controllers have been added and removed from the DOM so it can update its total.

Parent: line_items

connect() {
  this.element.addEventListener("lineItem:added", this.calculate.bind(this));
  this.element.addEventListener("lineItem:removed", this.calculate.bind(this));
}

Child: line_item

connect() {
  fire(this.element, "lineItem:added");
}

disconnect() {
  // This does not get fired because the element 
  // has already been removed from the DOM
  fire(this.element, "lineItem:removed");
}

To get around this, I have been storing this.element.parentNode on connect and then firing the event on the parentNode on disconnect, but this feels a bit clunky.

Child: line_item

connect() {
  this.parent = this.element.parentNode;
  fire(this.element, "lineItem:added");
}

disconnect() {
  fire(this.parent, "lineItem:removed");
}

Hello

Some time ago I tried to package a standard controller that I have been using to handle parent/children.
maybe it can help or you can extract out of it some solution for your issue.

They are several improvements possible to this package but so fare it has suited my needs.

1 Like

Hi Adrien,

Your conductor project has been on my radar for quite some time now. I’ve yet to adopt it because I’ve noticed the reluctance of the core Stimulus team to bless the use of the undocumented getControllerForElementAndIdentifier. Not sure if I’m just being overly paranoid :thinking:

@adrienpoly I just tried implementing conductor for my use case and it doesn’t appear to handle dashed controller names very well e.g. this['line-itemsController'] instead of this.lineItemsController

Could very well be, I don’t think I ever tested that with this package. Thanks for poping up the issue