I would like to know if it is a good practice to use the event to communicate between functions inside ExpressJS?. If yes how can I send arguments along my emit event?
-
What does "communicate between functions" mean?Dave Newton– Dave Newton2014-12-02 18:00:29 +00:00Commented Dec 2, 2014 at 18:00
-
Most javascript implementations are based on event loops (nodejs is specifically based on event loops) -- so using events is definitely good practice for some tasks -- could you be more specific and provide a code example.Soren– Soren2014-12-02 18:01:39 +00:00Commented Dec 2, 2014 at 18:01
-
Unfortunately I can't provide I code sample . but I can explain more my idea. the reason I am considering using events is this. when a user connects to my application an event must be triggered . this event contains the user information (id, name and other credentials). the event will call a function that runs in the background while the user is redirected to his home page.user2422940– user24229402014-12-03 08:50:59 +00:00Commented Dec 3, 2014 at 8:50
2 Answers
It depends. If you have truly asynchronous communications between functions then events are something to consider. "Truly" means that the thread of execution of a called function is interrupted with setInterval, nextTick or syncIO (just using callback is not necessarily asynchronous). If this is not the case, you cannot use events as they will be emitted before your calling function can set a listener on it.
Events require more work in the called function - you need to create an instance of EventEmitter and pass it back, on which a callee will set a listener. Then your called function emits event(s).
If your relationship between functions is one-to-one (request/reply) and the outcome is success/failure than it is easier to just have a callback.
If your asynchronously called function can emit events multiple times or there are more than a couple of outcomes, then events are a good fit.
As for arguments, please look at the doc: http://nodejs.org/api/events.html
emitter.emit(event, [arg1], [arg2], [...])
2 Comments
The API Reference: http://nodejs.org/api/events.html#events_emitter_emit_event_arg1_arg2
Here is an example:
var emitter = new EventEmitter();
emitter.on('stack', function(name, message) {
console.log("I got the event", name, message);
});
emitter.emit('stack, 'eventName', 'I like arguments');