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.

3
  • You need to access it from the detail property of the event, eg inside event callback eventVariable.detail.index Commented Nov 20, 2019 at 11:29
  • Possible duplicate of Create JavaScript custom event Commented Nov 20, 2019 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. Commented Nov 21, 2019 at 8:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.