EventEmitter是nodejs核心的一部分。很多nodejs对象继承自EventEmitter,用来处理事件,及回调。api文档地址:
http://nodejs.org/api/events.html#events_class_events_eventemitter
Event:
Many objects in Node emit events: a net.Server
emits an event each time a peer connects to it, a fs.readStream
emits an event when the file is opened. All objects which emit events are instances ofevents.EventEmitter
. You can access this module by doing: require("events");
Typically, event names are represented by a camel-cased string, however, there aren't any strict restrictions on that, as any string will be accepted.
Functions can then be attached to objects, to be executed when an event is emitted. These functions are calledlisteners. Inside a listener function, this
refers to the EventEmitter
that the listener was attached to.
Class: events.EventEmitter#
To access the EventEmitter class, require('events').EventEmitter
.
When an EventEmitter
instance experiences an error, the typical action is to emit an 'error'
event. Error events are treated as a special case in node. If there is no listener for it, then the default action is to print a stack trace and exit the program.
All EventEmitters emit the event 'newListener'
when new listeners are added and 'removeListener'
when a listener is removed.
emitter.addListener(event, listener)#
emitter.on(event, listener)#
Adds a listener to the end of the listeners array for the specified event.
server.on('connection', function (stream) {
console.log('someone connected!');
});
Returns emitter, so calls can be chained.
emitter.once(event, listener)#
Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});
Returns emitter, so calls can be chained.
emitter.removeListener(event, listener)#
Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.
var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Returns emitter, so calls can be chained.
emitter.removeAllListeners([event])#
Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's on an emitter that you didn't create (e.g. sockets or file streams).
Returns emitter, so calls can be chained.
emitter.setMaxListeners(n)#
By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.
emitter.listeners(event)#
Returns an array of listeners for the specified event.
server.on('connection', function (stream) {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
emitter.emit(event, [arg1], [arg2], [...])#
Execute each of the listeners in order with the supplied arguments.
Returns true
if event had listeners, false
otherwise.
Class Method: EventEmitter.listenerCount(emitter, event)#
Return the number of listeners for a given event.
Event: 'newListener'#
event
String The event namelistener
Function The event handler function
This event is emitted any time someone adds a new listener. It is unspecified if listener
is in the list returned by emitter.listeners(event)
.
Event: 'removeListener'#
event
String The event namelistener
Function The event handler function
This event is emitted any time someone removes a listener. It is unspecified if listener
is in the list returned byemitter.listeners(event)
.
/* EventEmitter发送和接收事件 HTTPServer和HTTPClient类,它们都继承自EventEmitter EventEmitter被定义在Node的事件(events)模块中,直接使用EventEmitter类需要先声明require('events'), 否则不必显式声明require('events'),因为Node中很多对象都无需你调用require('events')就会使用EventEmitter */ var events = require('events'); var util = require('util'); function Pulser(){ events.EventEmitter.call(this); } util.inherits(Pulser, events.EventEmitter); Pulser.prototype.start = function(){ var self = this; this.id = setInterval(function(){ util.log('>>>>pulse'); self.emit('pulse'); util.log('<<<<pulse'); }, 1000); } //定义了一个类Pulser,该类(通过util.inherits)继承自EventEmitter,它的作用是每隔一秒钟向所有监听器发送一个定时事件。 //start方法使用了setInterval这个函数来定期重复执行回调函数,并调用emit方法将pulse事件发送给每一个监听器 //使用Pulser对象 /* 创建了一个Pulser对象并处理其pulse事件,执行pulser.on('pulse'..)为pulse事件和回调函数建立联系 */ var pulser = new Pulser(); pulser.on('pulse', function(){ util.log('pulse received'); }); pulser.start(); //对象使用emit函数发送事件,所有注册到对应事件的监听器都可以收到事件; //通过调用.on方法注册监听器,参数是事件名,并用一个回调函数接收事件 //通常来说,有一些数据需要伴随着事件同时发送 self.emit('eventName', data1, data2, ..); //emitter.on('eventName', function(data1, data2,..){ //接收到事件后的操作 // });