Node(8) Events

来源:互联网 发布:杜蕾斯淘宝快递 编辑:程序博客网 时间:2024/06/01 09:07

How to create an event for the class:

You have to inherite fro events.EventEmitter to be able to emit and handle event

EventEmitter have on and emit method for handling events

on and addListener are basically the same


emitter.emit(event, [arg1], [arg2], [...])

Execute each of the listeners in order with the supplied arguments.


emitter.on(event, listener)

Adds a listener to the end of the listeners array for the specified event.


var util = require("util"); //util defines inheritevar events = require("events");//create new classvar MyStream = function(){events.EventEmitter.call(this);}//inherites events.EventEmitterutil.inherits(MyStream, events.EventEmitter);//write method emits data eventMyStream.prototype.write = function(data){this.emit( "data", data );}//create new instancevar stream = new MyStream();console.log( stream instanceof events.EventEmitter);//truestream.on( "data", function( data){//event listenerconsole.log( 'Received data: "' + data + '"' );})stream.write("It works!"); //Received data: "It works!"


原创粉丝点击