Can't use properties and methods from the object passed as an argument to the Phaser event handler function [closed]

18 hours ago 1
ARTICLE AD BOX

I'm developing a card game using Phaser, and I ran into some really weird behaviour.
I'm using built in Phaser EventEmitter object for handling some card effects.

EventEmitter example:

const eventEmitter = new Phaser.Events.EventEmitter(); eventEmitter.on('event-name', (...args) => { ... }); eventEmitter.emit('event-name', arg1, arg2);

When I pass an object as an argument to the eventHandler function, and when I try to read any property from that object using dot notation, the result is undefined, when I try to call a method from that object, it throws an exception "obj.func is not a function", but when I log that object in the console, it prints the object with all the properties and methods.

I can find a workaround for this problem, but I want to understand why this is happening.

What's going on here?

Code:

import Phaser from "phaser"; enum Events { TEST = "TEST", } class EventsHandler { private eventEmitter = new Phaser.Events.EventEmitter(); public on(event: Events, fn: (...args: any[]) => void) { this.eventEmitter.on(event, fn); } public off(event: Events, fn: (...args: any[]) => void) { this.eventEmitter.off(event, fn); } public emitEvent(event: Events, ...args: any[]) { this.eventEmitter.emit(event, args); } } export class Game extends Phaser.Scene { eventsHandler: EventsHandler = new EventsHandler(); constructor() { super("Game"); } create() { const testEventListener = (...args: any[]) => { console.log(args[0]); //prints object with all the properties and methods console.log(args[0].testProperty); //prints undefined console.log(args[0].sayHello()); //throws an exception "args[0].sayHello is not a function" }; this.eventsHandler.on(Events.TEST, testEventListener); const testObj = { sayHello: () => console.log("hello"), testProperty: "hello", }; this.eventsHandler.emitEvent(Events.TEST, testObj); } }

Exception:

Uncaught TypeError: args[0].sayHello is not a function at EventEmitter2.testEventListener (Game.ts:34:27) at EventEmitter2.emit (phaser.js:198:35) at EventsHandler.emitEvent (Game.ts:19:23) at Game.create (Game.ts:42:24)
Read Entire Article