Event Emitters

In node.js an event can be described simply as a string with a corresponding callback. An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted.

Event emitter as it sounds is just something that triggers an event to which anyone can listen.

Different libraries offer different implementations and for different purposes, but the basic idea is to provide a framework for issuing events and subscribing to them.

Here is an Example from jQuery:

// Subscribe to event.

$('#foo').bind('click',function()
{
    alert("Click!");
});
// Emit event.

$('#foo').trigger('click');

Here is an example od code snippet that explains how events are emitted in node:

var example_emitter = new (require('events').EventEmitter);

example_emitter.on("test", function () { console.log("test"); });

example_emitter.on("print", function (message) { console.log(message); });

example_emitter.emit("test");

example_emitter.emit("print", "message");

example_emitter.emit("unhandled");

And here an example of doing it from the REPL:

> var example_emitter = new (require('events').EventEmitter);

{}

> example_emitter.on("test", function () { console.log("test"); });

{ _events: { test: [Function] } }

> example_emitter.on("print", function (message) { console.log(message); });

{ _events: { test: [Function], print: [Function] } }

> example_emitter.emit("test");

test //console.log'd

true //return value

> example_emitter.emit("print", "message");

message //console.log'd

true //return value

> example_emitter.emit("unhandled");

false //return value

results matching ""

    No results matching ""