nodejs EventEmitter

来源:互联网 发布:排课软件km1199 编辑:程序博客网 时间:2024/05/19 13:19

Many objects in Node emit events: a net.Server emits an event each timea peer connects to it, afs.readStream emits an event when the file isopened. 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 eventis emitted. These functions are calledlisteners. 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 thelistener has already been added. Multiplecalls passing the same combination ofevent 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_eventxiaoming eat ricelistener 2 response to some_event


0 0
原创粉丝点击