nodejs EventEmitter

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值