Events
events模块是node的核心模块之一,几乎所有常用的node模块都继承了events模块,比如http、fs等。
模块本身非常简单,API虽然也不少,但常用的就那么几个,这里举几个简单例子。
例子1:单个事件监听器
1var EventEmitter = require('events');23class Man extends EventEmitter {}45var man = new Man();67man.on('wakeup', function(){8 console.log('man has woken up');9});1011man.emit('wakeup');12// 输出如下:13// man has woken up
例子2:同个事件,多个事件监听器
可以看到,事件触发时,事件监听器按照注册的顺序执行。
1var EventEmitter = require('events');23class Man extends EventEmitter {}45var man = new Man();67man.on('wakeup', function(){8 console.log('man has woken up');9});1011man.on('wakeup', function(){12 console.log('man has woken up again');13});1415man.emit('wakeup');1617// 输出如下:18// man has woken up19// man has woken up again
例子3:只运行一次的事件监听器
1var EventEmitter = require('events');23class Man extends EventEmitter {}45var man = new Man();67man.on('wakeup', function(){8 console.log('man has woken up');9});1011man.once('wakeup', function(){12 console.log('man has woken up again');13});1415man.emit('wakeup');16man.emit('wakeup');1718// 输出如下:19// man has woken up20// man has woken up again21// man has woken up
例子4:注册事件监听器前,事件先触发
可以看到,注册事件监听器前,事件先触发,则该事件会直接被忽略。
1var EventEmitter = require('events');23class Man extends EventEmitter {}45var man = new Man();67man.emit('wakeup', 1);89man.on('wakeup', function(index){10 console.log('man has woken up ->' + index);11});1213man.emit('wakeup', 2);14// 输出如下:15// man has woken up ->2
例子5:异步执行,还是顺序执行
例子很简单,但非常重要。究竟是代码1先执行,还是代码2先执行,这点差异,无论对于我们理解别人的代码,还是自己编写node程序,都非常关键。
实践证明,代码1先执行了
1var EventEmitter = require('events');23class Man extends EventEmitter {}45var man = new Man();67man.on('wakeup', function(){8 console.log('man has woken up'); // 代码19});1011man.emit('wakeup');1213console.log('woman has woken up'); // 代码21415// 输出如下:16// man has woken up17// woman has woken up
例子6:移除事件监听器
1var EventEmitter = require('events');23function wakeup(){4 console.log('man has woken up');5}67class Man extends EventEmitter {}89var man = new Man();1011man.on('wakeup', wakeup);12man.emit('wakeup');1314man.removeListener('wakeup', wakeup);15man.emit('wakeup');1617// 输出如下:18// man has woken up