Stimulus Discourse

Share targets between controllers

I’m trying to build a complex component, and would like to break it down into multiple Stimulus controllers to make my work more manageable. Each of these controllers will handle their own small part of the component, but they share a target called fragment.

I started by building a ParentController that looks a bit like this:

import { Controller } from 'stimulus';

export default class extends Controller {
  static targets = ['fragment'];

  get visibleFragments(){
    return this.fragmentTargets().filter(fragment => !fragment.classList.contains('hidden'));
  }
}

Then I started making my other controllers inherit from it:

import ParentController from './parent_controller';

export default class extends ParentController {
  static targets = ['fragment'];

  someAction () {
    this.visibleFragments.forEach((fragment) => {
      // Do something
    });
  }
}

This approach has two problems:

  1. Every child controller must declare ‘fragment’ as a target (static targets = ['fragment']);
  2. Every fragment element must declare its a target of said controller (data-target="child1.fragment child2.fragment);

So what I’d like to know is:

  1. Is there a way to make child controllers inherit their parent’s targets? What if they also declare their own targets?
  2. Is there a way to change the which prefix Stimulus uses in the querySelector to search for the targets? (parent.fragment instead of child.fragment)