Monday 29 May 2017

Updating global variables with NodeJS

I'm beginner to NodeJS, so I'm not entirely sure what the best method to achieve this would be. Basically I want to create a global variable with a string, for instance 'USD', that would get updated whenever my 'set currency' event is fired. I want it to remain that way until the event is called again.

I am using EventEmitter to fire off some events, in one of my files I have the following.

 var event = require('./events');

  if (msg.content.includes('!currency set currency')) {
    split = msg.content.split(' ');
    event.emit('setCurrency', split[3])
  }

And then inside the events file I'm doing something like the following.

var exchangePref;

var event = new events.EventEmitter();


event.on('setExchange', (exchange) => {
   exchangePref = exchange;
   return exchangePref;
});

modules.exports = event;

I understand that re-writing the variable inside a callback isn't going to do what I need it to do, but I'm quite lost with how to achieve what I need it to do due to the modules.exports = event part at the bottom, the calling function simply never gets the data. I've played around with creating a constructor, but even still I couldn't get it to work.

Any suggestions/ideas would be greatly appreciated.



via James Ives

No comments:

Post a Comment