github / catalyst

Catalyst is a set of patterns and techniques for developing components within a complex application.
https://github.github.io/catalyst/
MIT License
1.36k stars 50 forks source link

Event from parent to child (v1.6.0) #309

Closed glomepe closed 1 year ago

glomepe commented 1 year ago

When I try to retrieve an event from a component declared as parent (or parent of parent, etc..), the child component doesn't seem to want to retrieve it.

It would be nice to have a feature that would allow to trigger an event launched in a parent component in a child.

I haven't found an equivalent way to do this kind of thing on catalyst, but it would be nice to have this kind of feature.

glomepe commented 1 year ago

This workaround is ugly but it work:

In your dom

<parent-component>
    <child-component data-targets="parent-component.bubbleables">
        <!-- some code here -->
    </child-component>
</parent-component>

In your parent component

import { controller, targets } from "@github/catalyst";

@controller
class ParentComponentElement extends HTMLElement {
    @targets bubbleables!: HTMLElement[];

    // call when you need to dispatch event to child
    private dispatchEventToBubbleables(eventName: BusEvents): void {
        const event = new CustomEvent(eventName);

        this.bubbleables.forEach((element) => element.dispatchEvent(event));
    }
}

In your child components

import { controller } from "@github/catalyst";

@controller
class ChildrenComponentElement extends HTMLElement {
    connectedCallback(): void {
        this.addEventListener('eventName', this.doSomething);
    }

    private doSomething(): void {
        console.log('event received 🤩🤩🤩');
    }
}
keithamus commented 1 year ago

Thanks for the issue!

Events should only go upwards, from children to parents. Parents can use direct communication via the child’s API - directly calling methods and accessing properties. You can use targets to help easily query child components and use their class methods.