1

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.

4

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.

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

You can add second parameter as follows:

const selectedEvent = new CustomEvent('custevent', {
    detail: this.someData,
    secondParam : this.anotherData
});
  • i tried this, but it doesn't work, secondParam is always undefined in Parent component. – gs650x Dec 10 '19 at 10:31
  • are you sure you are accessing the second param in parent component using exact same name ? – Shamina Dec 10 '19 at 10:36
  • Yes I am 100% sure – gs650x Dec 10 '19 at 10:36
  • @gs650x based on Sanket Kumar answer, apply correct naming of custom event and try again. regarding adding second param, i've seen this done before, so the issue may be coming from the naming – Shamina Dec 10 '19 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.