reactjsnpmeventsphaser-framework

How to use npm's 'events' module in Reactjs for eventEmitters


I want to use npm's 'events' module in my React application. I have a game developed in phaserjs which also has level editor. The 'events' will used to communicate with the game module. Folder Structure from root

Some one had done same thing but in angular -- in it's app.js

const eventEmitter = require('events').EventEmitter();
window.eventEmitter = eventEmitter;
eventEmitter.on('loaded', () => { console.log('\n\ncreator loaded\n\n') })

and in other states of his angular app he would just take --

const eventEmitter = window.eventEmitter;
eventEmitter.emit('start game');

Here's the link to that project, look in browser module,app.js and also browser/states/createlevel

I want to do the same exact thing,my project is similar but game logic is different.

The game module has all the neccesary events emitters and listeners setup

I have tried setting up window.eventsEmitter() in my index.js and using that in other components. Problem starts here, how do I use it in a React class or a function,should it be in constructor or should I set it up in lifecycle methods,or should I put it completely different js file and include it? I tried most(except for last one) but failed.

I also searched about how to do it, haven't got exactly what I'm looking for..Any suggestion will be really helpful. Thanks in advance.


Solution

  • That syntax for EventEmitter doesn't seem to work. I used the example from the npm page here (and it works) - https://www.npmjs.com/package/events

    Add this to App.js:

    const eventEmitter = require('events');
    window.ee = new eventEmitter();
    ee.on('loaded', () => { console.log('\n\ncreator loaded\n\n') })
    ee.on('test', () => { console.log('\n\ntest fired\n\n') })
    

    Then from any component constructor (or componentdidmount etc) :

    constructor( props ) {
        super( props );
        ee.emit('test', 'asdf')
    }