Search code examples
javascripttypescriptlit-element

LitElement click function is executed twice


i have two components sdk-button and an upper-component

in my sdk-button i have the following simple code:

public render() {
    return html`
    <button  @click=${this._handleClick}>${this.text}</button>

`;
}

_handleClick() {
    let click = new Event('click');
    this.dispatchEvent(click);
}

This dispatches a click event so in my upper-component i have the following code:

public render() {
    return html`
  <h1>Hello, ${this.test}!</h1>
  <sdk-button   @click="${() => { this.changeProperty() }}" text="Click"></sdk-button>
`;
}

changeProperty() {
    let randomString = Math.floor(Math.random() * 100).toString();
    console.log(randomString)
}

This works however the changeProperty is fired twice. can anyone tell me why this is happening?


Solution

  • I am pretty sure that's because there are two click events: the native one from the button which bubbles up, and the one you dispatch manually. Try to either use a custom event with a different name or remove the dispatch from the sdk-button and use the native one.