3

I have a below event in LWC

const selectedEvent = new CustomEvent('custEvent', {
    detail: this.someData;
});

this.dispatchEvent(selectedEvent );

I also want to pass this.anotherData;

Could someone please confirm if is there anyway to pass 2 parameters to an event or do I need to create another event.

1 Answer 1

8

Pass a JS Object direct into detail

const selectedEvent = new CustomEvent('custevent', {
    detail: {
        type: "Fiat",
        model:"500",
        color:"white"
    } 
});

Access the object in your listener method and get the value from object as:-

hndlecustEvent(event) {
    this.value1 = event.detail.type;
    this.value2 = event.detail.model;
  }

Another thing, The CustomEvent() constructor has one required parameter, which is a string indicating the event type. As a component author, you name the event type when you create the event. You can use any string as your event type. However, we recommend that you conform with the DOM event standard.

  • No uppercase letters
  • No spaces
  • Use underscores to separate words

Your event name is custEvent which is not valid as it has uppercase letter. You should use only lowercase.

Update:-

According to CustomEvent() documentation on MDN,

Parameters

  1. typeArg:- A DOMString representing the name of the event.
  2. customEventInit (Optional):- A CustomEventInit dictionary, having the following fields:

    "detail", optional and defaulting to null, of type any, that is an event-dependent value associated with the event.

The CustomEventInit dictionary also accepts fields from the EventInit dictionary.

So, You can pass the value only in detail.

3
  • yes I am using this approach only, but can we use something like Shamina suggested?
    – gs650x
    Commented Dec 10, 2019 at 10:32
  • I believe that route will not work. You have to use detail to pass the value. Commented Dec 10, 2019 at 11:27
  • Thank you for your help
    – gs650x
    Commented Dec 11, 2019 at 5:52

You must log in to answer this question.

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