简体   繁体   中英

StencilJS Event & Listen of sibling child's of a parent clashing with multi-instance

I have parent component has two child components(siblings). These child component has event and listen behaviors. Now I need multiple instance of this parent component in a web page where I have an issue, all the instances interacts when we trigger the event. Since the Listen decorator's Target is attached to body. As far as I know if it is 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 should not interact with the multi instance scenario of the parent component?

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> ;
  }
}```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM