LWC Callback – How to Pass Callback to Child Lightning Web Component

I have a parent component like

export default class Parent extends LightningElement {
   onResult() {
      this.doSomething();
   }
}

<template>
    <c-child result-callback={onResult}></c-child>
</template>

and a child component:

export default class Child extends LightningElement {
   @api resultCallback;

   onClick() {
      this.resultCallback();
   }
}

<template>
    <button onclick={onClick}>click me</button>
</template>

The issue seems to be that when this.resultCallback() runs, which calls the parent's onResult method, this is still the child component.

LWCs seem to magically autobind methods, so I'm not sure if this a LWC bug or if I'm missing something.

How does a parent element pass a callback to a child LWC?

Best Answer

you have to bind the method before passing it to the child.

Ex1: arrow function is auto bind.

export default class Parent extends LightningElement {

   onResult = () => {
      this.doSomething();
   }
}
----
<template>
    <c-child result-callback={onResult}></c-child>
</template>
Ex2: binding it in the constructor.

export default class Parent extends LightningElement {
   result = this.onResult.bind(this)

   onResult() {
      this.doSomething();
   }
}
----
<template>
    <c-child result-callback={result}></c-child>
</template>
Related Topic