常用事件
/*
调用events模块,获取events.EventEmitter对象
*/
var EventEmitter = require('events').EventEmitter;
var events = new EventEmitter();
/*
EventEmitter.on(event, listener) 为事件注册一个监听
参数1:event 字符串,事件名
参数2:回调函数
*/
events.on('some_events', function(foo, bar) {
console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
});
console.log('第一轮');
events.emit('some_events', 'Wilson', 'Zhong'); // 返回true
console.log('第二轮');
events.emit('some_events', 'Wilson', 'Z');
events.on('whatName',function(name){
console.log('My name is '+name);
});
events.emit('whatName','finder');
其它事件
emitter.addListener(event, listener)
emitter.on(event, listener)
emitter.once(event, listener)
emitter.removeListener(event, listener)
emitter.removeAllListeners([event])
emitter.setMaxListeners(n)
EventEmitter.defaultMaxListeners
emitter.listeners(event)
emitter.emit(event[, arg1][, arg2][, ...])
Class Method: EventEmitter.listenerCount(emitter, event)
特殊的事件Error
引用自Node.js开发指南:EventEmitter 定义了一个特殊的事件 error,它包含了“错误”的语义,我们在遇到 异常的时候通常会发射 error 事件。当 error 被发射时,EventEmitter 规定如果没有响 应的监听器,Node.js 会把它当作异常,退出程序并打印调用栈。我们一般要为会发射 error 事件的对象设置监听器,避免遇到错误后整个程序崩溃
事件的继承
var util = require("util");
var events = require("events");
function MyStream() {
events.EventEmitter.call(this);
}
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
}
var stream = new MyStream();
console.log(stream instanceof events.EventEmitter); // true
console.log(MyStream.super_ === events.EventEmitter); // true
stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"