nodejs触发事件的两种方式:
方式之一:通过实例化events.EventEmitter
//引入events模块 var events = require('events'); //初始化events.EventeEmitter()对象 var eventEmitter = new events.EventEmitter(); //声明一个回调函数 function ring = function(){console.log("Ring,ring ,ring!!!!")} //采用eventEmitter中的on方法绑定事件 eventEmitter.on('ring',ring); //触发绑定所有绑定在on上的事件 eventEmitter.emit('ring');
方法之二:通过继承eventsEventEmitter原型来实现时间的绑定触发
var events = require('events'); var util = require('util'); function ring(){ events.EventEmitter.call(this); this.open = function(){ console.log("ring inherits from events.EventEmitter"); this.emit('open'); } } util.inherits(ring,events.EventEmitter); var ring_instance = new ring; ring_instance.on('open',function(){console.log("Inherits events.EventEmitter and use on bind function")}); ring_instance.open();
需要说明的一点是在javascript 原型需要实例化之后才可以使用 也就是new prototype;