Node.js中的事件

var util = require("util"); //导入util模块

var events = require("events"); //导入events模块

module.exports = MyStream;



function MyStream() {

    events.EventEmitter.call(this); //call方法使得MyStream对象继承了EventEmitter对象上的方法

}

util.inherits(MyStream, events.EventEmitter);   //使用inherits方法



MyStream.prototype.write = function (data) {    //MyStream对象扩展了一个write方法,它可以使用emit触发事件

    this.emit("data", data);

};



var stream = new MyStream();    //构建一个stream对象



console.log("stream instanceof events.EventEmitter: " + (stream instanceof events.EventEmitter)); //判断stream对象是不是EventEmitter对象的实例,这里为true

console.log("MyStream.super_ === events.EventEmitter: " + (MyStream.super_ === events.EventEmitter)); //MyStream的父类是不是EventEmitter,这里为true



stream.on("data", function (data) {

    console.log('Received data: "' + data + '"');

});

stream.write("It works1!");

stream.write("It works2!");

运行结果如下:

image

涉及模块:eventsutil

核心函数:util.inherits

你可能感兴趣的:(node.js)