美文网首页
nodejs的events包

nodejs的events包

作者: 袁韩 | 来源:发表于2016-03-02 21:01 被阅读348次

    Vue-hackernews时,在/store/index.js中发现了对events库的引用。想不到在前端代码中还可以引用nodejs的库,这是webpack的功劳吧 ? 还需要再检查一下!另外,看着代码,发现在前端中使用nodejs的库竟然完全不生疏。趁着机会,正好学习一下events库。

    引入

    //normal
    var EventEmitter  = require('events')['EventEmitter'];
    //es6
    import {EventEmitter} from 'events'
    //translated to 
    var _events = require('events')
    var store = new _events.EventEmitter()
    

    主要API

    • The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.
    • Using the eventEmitter.once() method, it is possible to register a listener that is immediately unregistered after it is called
    • As a best practice, developers should always register listeners for the 'error' event
    myEmitter.on('error', (err) => {
      console.log('whoops! there was an error');
    });
    
    • All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.

    The EventEmitter instance will emit it's own 'newListener'
    event before a listener is added to it's internal array of listeners.

    • By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individualEventEmitter instances using the emitter.setMaxListeners(n) method

    相关文章

      网友评论

          本文标题:nodejs的events包

          本文链接:https://www.haomeiwen.com/subject/cdvnkttx.html