Skip to content Skip to sidebar Skip to footer

Javascript: Declare Custom Event With Custom Parameters

I'm coding a Javascript Web app and I want to send a custom event when a controller button is pressed. That event should have custom parameters: event.index, event.player2, and eve

Solution 1:

Apparently, there is no way to do this. The best workaround JS has to offer is this:

varevent = new CustomEvent('PutYourEventNameHere', {
  detail: { // filled with sample values
    index: 0,
    player2: false,
    button: 1
  }
});

But this won't set the properties as you would expect.

event.index
>>>undefined
event.player2
>>>undefined
event.button
>>>undefined

All you can do with a CustomEvent is to set the parameter detail instead, resulting in this kind of behavior:

event.detail.index
>>>0
event.detail.player2
>>>false
event.detail.button
>>>1

Conclusion: If you're making a custom event, you can only define detail. But you can define detail as an object to add multiple custom properties. It's ugly, but that's what we have.

Post a Comment for "Javascript: Declare Custom Event With Custom Parameters"