7

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?

1

1 Answer 1

10

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>
3
  • oh nice, I didn't realize LWCs supported fat arrow. Thanks!
    – Andy Ray
    Jan 15, 2020 at 17:48
  • hi Andrius Satraitis, Could you explain for me why use arrow function ? I don't undertand about it
    – Dung Phan
    May 20, 2020 at 5:36
  • @ptdung0312 Arrow functions do not have their own this. See: No separate this Jul 29, 2020 at 0:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .