1

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 event.button. However, none of them are defined in the resulting event. This is what I tried so far:

I first declared the event as follows:

var testEvent = new Event('controllerPress', {
  index: 0,
  player2: false,
  button: 12
});

After that didn't work, I looked up some Q&As online (like this), and redeclared the event as such...

var testEvent = new Event('controllerPress', {
  detail: {
    index: 0,
    player2: false,
    button: 12
  }
});

...but to no avail. I looked again and changed the declaration to use CustomEvent...

var testEvent = new CustomEvent('controllerPress', {
  detail: {
    index: 0,
    player2: false,
    button: 12
  }
});

...but testEvent.index is still undefined. What am I missing?

EDIT: This is not a duplicate of “Create JavaScript custom event” because that asks how to create a custom event at all, but this asks how to add a custom property to that custom event.

haley
  • 845
  • 1
  • 7
  • 15
  • You need to access it from the `detail` property of the event, eg inside event callback `eventVariable.detail.index` – Patrick Evans Nov 20 '19 at 11:29
  • Possible duplicate of [Create JavaScript custom event](https://stackoverflow.com/questions/23344625/create-javascript-custom-event) – Jayakumar Thangavel Nov 20 '19 at 16:16
  • 1
    @GoodSamaritan No, because that asks how to create an event at all, while this asks how to add a custom property to that custom event. – haley Nov 21 '19 at 08:02

1 Answers1

0

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

var event = 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.

haley
  • 845
  • 1
  • 7
  • 15