StencilJS Event & Listen for sibling children clashing with multi-instance

754 views Asked by At

I have a parent component which has two child components (siblings). These child components have event and listen behaviors. Now I need multiple instance of this parent component in a web page, but I run into an issue where all the instances interact when we trigger the event, since the Listen decorator's Target is attached to body. As far as I know, if there are sibling components, we need to use the target as body and if it is parent/child then it is not necessary to use the target.

Is there any work around to restrict this event trigger to not interact with the multi-instance scenario of the parent component?

1

There are 1 answers

2
Morteza Ebrahimi On

Use Listen to listen to the events dispatched to the window. Parent-child interactions should go through the event attributes. Look at this sample!

Child

import { Component, EventEmitter, h, Event, Prop } from '@stencil/core';

@Component({
  tag: 'child-component',
  shadow: true,
})
export class MyChildComponent {
  @Prop() name : string;
  @Event() componentClicked: EventEmitter<string>;

  clickHandler = (event: Event)=>{
    event.preventDefault(); 
    event.stopPropagation();
    this.componentClicked.emit(this.name)
  }

  render() {
    return <div onClick={this.clickHandler.bind(this)}>{this.name}</div>;
  }
}

Parent



@Component({
  tag: 'parent-component',
  shadow: true,
})
export class MyParentComponent {

  clickHandler = (event: CustomEvent)=>{
    event.preventDefault(); 
    event.stopPropagation();
    console.log(event.detail)
  }

  render() {
    return<Host>
      <child-component name="1" onComponentClicked={this.clickHandler.bind(this)} />
      <child-component name="2" onComponentClicked={this.clickHandler.bind(this)} />
      <child-component name="3" onComponentClicked={this.clickHandler.bind(this)} />
      <child-component name="4" onComponentClicked={this.clickHandler.bind(this)} />
    </Host> ;
  }
}```