Many objects in Node emit events: a net.Server emits an event each timea peer connects to it, a fs.readStream emits an event when the file isopened. All objects which emit events are instances of events.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 eventis emitted. These functions are called listeners. Inside a listenerfunction, this refers to the EventEmitter that the listener wasattached to.
Class: events.EventEmitter#
To access the EventEmitter class, require('events').EventEmitter.
When an EventEmitter instance experiences an error, the typical action isto 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 stacktrace and exit the program.
All EventEmitters emit the event 'newListener' when new listeners areadded 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.No checks are made to see if the listener has already been added. Multiplecalls passing the same combination of event and listener will result in thelistener being added multiple times.
server.on('connection', function (stream) {
console.log('someone connected!');
});
Returns emitter, so calls can be chained.
emitter.emit(event, [arg1], [arg2], [...])#
Execute each of the listeners in order with the supplied arguments.
Returns true if event had listeners, false otherwise.
例子:
var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();
event.on('some_event', function(who, opcode, opobject){
console.log("listener 1 response to some_event");
console.log("%s %s %s\n", who, opcode, opobject);
});
event.on('some_event', function(){
console.log("listener 2 response to some_event");
});
setTimeout(function(){
event.emit('some_event', "xiaoming", "eat", "rice");
}, 1000);
结果输出:
listener 1 response to some_event
xiaoming eat rice
listener 2 response to some_event
本文介绍了Node.js中EventEmitter类的基本用法,包括如何监听和触发事件,并通过实例展示了如何使用EventEmitter来响应特定事件。
931

被折叠的 条评论
为什么被折叠?



