emitters and forgetters in an event driven app - 401-advanced-javascript-aimurphy/seattle-javascript-401n13 GitHub Wiki
.emit
is like a radio wave and.on
is your tuner.-- Aileen (yea, I self-quoted 😎)
Every time you click a button or press a key while interacting with a webpage, you've just executed an event. Events trigger functions that can cause the interface to change or react to the user.
Major Players:
-
event handlers: callback functions that are triggered when the event happens
-
main loop that listens for events and calls on the appropriate event handlers
Tools
node.js has a cool module that has done some of the event coding for you: eventemitter
the evenetemitter class is accessed through the events module so you'll need to setup the dependency:
const EventEmitter = require('events').EventEmitter;
const myEventEmitter = new EventEmitter;
Put them to work!
First, decide what event you want to react to and then write a function for it. Event emitter will act as the link from that event to your responding function. for example: say you have a chatroom and you want to notify folks whenever somebody enters the chat
write the function for the notification--aka, the event handler:
function enteredChat(username){
//assuming we have a function to alert all, we will put it in here as a callback
alertAll(`${username} has entered the chat, y'all!`);
}
Now hook-up the event listener (which uses the event emitters .on
method, that's how we listen):
myEventEmitter.on('enteredChat',enteredChat);
nothing is happening yet because we're just listening. we aren't fully wired. We need the listener to meet the handler, and that's the .emit
method. So for our chat, we may want to do this upon login. Soon as the person logs into chat, we'll announce them. So the emitter for that would be:
function login(username){
myEventEmitter.emit('enteredChat', username);
}
what if you want to forget?
Stop the listening...
you might want to do this for performance or to avoid memory leaks. Why use it if you no longer need it, right? Keep things simple and tidy.
morerandomnotes
asynchronous event-driven architecture where emitter objects emit events that cause listener objects to be called.
Purpose to avoid issues of complexity and collision
an event emitter object emits its event the event listener object then calls all listeners linked to that event all functions attached to the event are synchronously called.
to go async, use setImmediate() or process.nextTick()
sources
meduim: nodjs event emitter explained
alligator.io: event-driven programming