Joe Karlsson
progress. tech. cats. coffee. art. food. photog. mpls.
var EventEmitter = require('events');
Objects that are subclasses of EventEmitter
may have functions attached to them.
These functions are called listeners, or event handlers,
and are invoked when an event is emitted by that object.
Events are named using a string, such as "complete" or "error".
When the event handler is invoked by an event being emitted,
the context of the event handler function
is the object that it is listening on.
emitter.addListener(event:String, listener:Event->Void)
alias emitter.on(args)
^---- callback function
v---- event name
emitter.emit(event:String);
emitter.removeListener(event:String, listener:Event->Void)
^---- event handle function
v---- event name
function Timer () {
setInterval(function () {
// do something every 1000ms
}, 1000);
}
var EventEmitter = require('events');
function Timer () {
EventEmitter.call(this);
setInterval(function () {
// do something every 1000ms
}, 1000);
}
Timer.prototype = new Object(EventEmitter.prototype, {
constructor: {
value: EventEmitter,
configurable: true,
enumerable: true,
writable: true
}
});
var EventEmitter = require('events');
var util = require('util');
function Timer () {
EventEmitter.call(this);
setInterval(function () {
// do something every 1000ms
}, 1000);
}
util.inherits(Timer, EventEmitter);
for easier inheritence
var myTimer = new Timer();
myTimer.addListener('tick', function(){
process.stdout.write('tick \n');
});
function Timer () {
EventEmitter.call(this);
var self = this;
setInterval(function () {
self.emit('tick');
}, 1000);
}
function Timer () {
EventEmitter.call(this);
var self = this;
var i = 0;
setInterval(function () {
self.emit('tick', { interval : i++ });
}, 1000);
}
like callback arguments
myTimer.addListener('tick', function(event){
process.stdout.write('tick ' + event.interval + '\n');
});
function tickHandler(event){
process.stdout.write('tick ' + event.interval + '\n');
}
myTimer.addListener('tick', tickHandler);
function tickHandler(event){
process.stdout.write('tick ' + event.interval + '\n');
if(event.interval == 5){
myTimer.removeListener('tick', tickHandler);
}
}
myTimer.addListener('tick', tickHandler);
function tickHandler(event){
process.stdout.write('tick ' + this.i + '\n');
if(this.i == 5){
this.removeListener('tick', tickHandler);
}
}
myTimer.addListener('tick', tickHandler);
function Timer () {
EventEmitter.call(this);
var self = this;
this.i = 0;
setInterval(function () {
self.emit('tick', { interval : self.i++ });
}, 1000);
}
look for objects or classes that extend EventEmitter
it means you can listen for events that it will emit
check the class api documentation or source code
for what events it will emit, and the contents of the event object it passes back to the handler
emitter.on('data', function(event){...});
What are you ? -----v
^----- What other events do you emit?
By Joe Karlsson