Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

events 事件

基础

源代码:lib/events.js

作用:提供触发事件的机制,并让绑定到该事件的函数被按顺序同步调用

用法

  • 引入

    • es6
      import { EventEmitter } from 'events';
      
    • commonjs
      const EventEmitter = require('')
      
  • 创建对象并添加事件监听

    let emitter = new EventEmitter();
    
    emitter.on('myEvent', () => {
        console.log('hi 1');
    });
    
    emitter.on('myEvent', () => {
        console.log('hi 2');
    });
    
  • 触发事件

    emitter.emit('myEvent');
    
    • 之后会同步执行,输出 hi 1 和 hi 2
  • 不断触发,会死循环的例子

    emitter.on('deadEvent', () => {
        console.log('hi');
        emitter.emit('deadEvent');
    });
    
    emitter.emit('deadEvent');
    
  • 再次添加监听,不会死循环的例子

    emitter.on('safeEvent', function sth () {
        emitter.on('safeEvent', sth);
        console.log('hi');
    });
    
    emitter.emit('safeEvent');