3

While passing data from Child Component to Parent Component, I can definitely Dispact Custom Event and populate the 'detail' property. However, it seems (like React), I can also pass callback function from the Parent to Child and execute the callback with data on event. Parent.Html

    <template>
      <c-child call-back={handleNotification}></c-child>
      {message}
    </template>

Parent.JS

 import { LightningElement, track, api } from 'lwc';

 export default class App extends LightningElement {

        message=''

        //Callback
        handleNotification=(val)=>{
            this.message=val;
        }


    }

Child.HTML

    <template>
    <div>
        <lightning-button label='Click here' variant='brand' onclick={raiseEvent}></lightning-button>
    </div>
</template>

Child.JS

import { LightningElement, track, api } from 'lwc';

export default class Child extends LightningElement {
    @api callBack;

    raiseEvent=()=>{
        console.log('raising Event');
        // DISPATCH EVENT or CaLL Callback ??
        this.callBack('Deep');
    }

}

Which pattern should be used one?

1
  • Just dispatch the event from the child and handle it in the parent, use the on<eventname>={handlerMethod} in the parent. It is best practice to keep the event name all lowercase. Commented May 5, 2020 at 8:12

2 Answers 2

0

The pattern of passing in callbacks does not exist in the documentation at all, as far as I can recall, either the Salesforce-branded version or the OSS version. As such, I would say it is idiomatic to use the event-driven version by default, unless you have some really compelling reason to use a callback.

I would have concerns about using callbacks being Aura-compatible (e.g. an Aura component calls a LWC, then it passes the data back to Aura), and since its undocumented, I would also be concerned that this behavior may be blocked in the future.

In any case, I recommend that you just stick with event-driven handlers in your project unless/until the documentation recommends using callbacks.

0
0

I agree with the answer provided by sfdcfox and would also point you to the fact that passing callbacks to child components is possible in Aura as well but the docs explicitly recommend events instead as outlined below.

From here:

"Although Aura.Action works for passing an action handler to a child component, we recommend registering an event in the child component and firing the event in the child’s controller instead. Then, handle the event in the parent component. The event approach requires a few extra steps in creating or choosing an event and firing it but events are the standard way to communicate between components."

You must log in to answer this question.

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