views:

462

answers:

2

I am trying to understand the purpose of addListener in node.js. Can someone explain please? Thanks! A simple example would be:

var tcp = require('tcp');
var server = tcp.createServer(function (socket) {
  socket.setEncoding("utf8");
  socket.addListener("connect", function () {
    socket.write("hello\r\n");
  });
  socket.addListener("data", function (data) {
    socket.write(data);
  });
  socket.addListener("end", function () {
    socket.write("goodbye\r\n");
    socket.end();
  });
});
server.listen(7000, "localhost");
+4  A: 

Due to the fact that Node.js works event-driven and executes an event-loop, registering listeners allow you to define callbacks that will be executed every time the event is fired. Thus, it is also a form of async. code structuring.

It's comparable to GUI listener, that fire on user interaction. Like a mouse click, that triggers an execution of code in your GUI app, your listeners in your example will be run as soon as the event happens, i.e. a new client connects to the socket.

PartlyCloudy
Ok so 'connect', 'data' or 'end' would be the name of event. But where and who defines these event names?
Jeffrey C
What exactly is 'event-looping'?
Jeffrey C
This depends on the source of event emission. Therefore exists the class EventEmitter. For available objects that are EventEmitters, like your (server-)socket, have a look in the documentation in order to find the event names.
PartlyCloudy
@Jeffrey: the event names are defined by whoever implements the class that dispatches the event. they are completely arbitrary. somewhere with the code of server, you will find something like "fireEvent", "triggerEvent" or "dispatchEvent", whatever it is called.
back2dos
I think the wikipedia article covers event loops well: http://en.wikipedia.org/wiki/Event_loop
PartlyCloudy
@Jeffrey: you might find this helpful: http://en.wikipedia.org/wiki/Event_loop ... although the explanation is a little more complicated than it needs to be :)
back2dos
+1  A: 

it registers a listener for an "event". Events are identified by strings, such as "connect" and "data". the second argument is a function, a so called "callback", also refered to as "event handler". Whenever a specific event occurs within the object the listeners have been registered to, all handlers are invoked.

node.js uses this, because it employs an asynchronous execution model, that can best be handled with an event-driven approach.

greetz
back2dos

back2dos
I understand the callback\async part. It's like publisher/subscriber so an event gets triggered and the event subscriber (the callback) then gets executed asynchronous (in a non blocking fashion). But I just couldn't get my head around the triggering bit. How does say "connect" get triggered by whom?
Jeffrey C
I think I need to read on EventEmitter section.
Jeffrey C