无法理解使用webpack和es6模块的EventEmitter正在发生什么

时间:2016-05-05 20:50:08

标签: javascript node.js ecmascript-6 webpack eventemitter

我正在尝试同时学习webpack和es6,并意识到需要某种事件总线。我是EventEmitters和构造函数的新手。我已经阅读了文档以及一些示例,但老实说,我不明白为什么下面的代码表现得像它那样。只有一个发射器的实例,所以为什么不是计数器或者removeListener能够找到任何东西?如果我将所有代码都放在一个文件中,那么它可以正常工作。

entry.js

import dVpEe from '../modules/eventEmitter';
const temp = new dVpEe();


var abc = function abc() {
    console.log('funciton a');
};

var b = function() {
    console.log('funciton b');
};

temp.evesdroppers('connection');
temp.hear('connection', abc);
temp.evesdroppers('connection');
temp.say('connection');
temp.hear('connection', b);
temp.evesdroppers('connection');
temp.say('connection');
temp.walk('connection', abc);
temp.say('connection');

eventEmitter.js

import events from 'events';
import util from 'util';

var EventEmitter = events.EventEmitter;

var dVpEe = function() {
    EventEmitter.call(this);
};

util.inherits(dVpEe, EventEmitter);

dVpEe.prototype.walk = function(event, cb, name) {
    console.log('%c' + (name || 'creeper') + '%c NOT listening for %c' + event, 'color: pink', 'color: white', 'color: pink');
    this.removeListener(event, cb);
};

dVpEe.prototype.say = function(event, name) {
    console.log('%c' + (name || 'someone') + '%c screamed %c' + event, 'color: pink', 'color: white', 'color: pink');
    this.emit(name);
};

dVpEe.prototype.evesdroppers = function(event) {
    var eventListeners = events.EventEmitter.listenerCount(this, event);
    console.log('%c' + eventListeners + '%c listner(s) for %c' + event, 'color: pink', 'color: white', 'color: pink');
};

dVpEe.prototype.hear = function(event, cb, name) {
    console.log('%c' + (name || 'creeper') + '%c listening for %c' + event, 'color: pink', 'color: white', 'color: pink');
    this.addListener(name, cb);
};

export default dVpEe;

输出中

0 listner(s) for connection
creeper listening for connection
0 listner(s) for connection
someone screamed connection
function a
creeper listening for connection
0 listner(s) for connection
someone screamed connection
function a
funciton b
creeper NOT listening for connection
someone screamed connection
funciton a
funciton b

1 个答案:

答案 0 :(得分:2)

这只是dVpEe.prototype.hear中的拼写错误。

dVpEe.prototype.hear = function(event, cb, name) {
    console.log((name || 'creeper') + ' listening for "' + event + "'");
    this.addListener(name, cb); // ouch!
};

我还建议将deprecated EventEmitter.listenerCount替换为emitter.listenerCount

dVpEe.prototype.evesdroppers = function(event) {
    var eventListeners = this.listenerCount(event);
};

由于您使用的是ES6,我建议使用class语法,它更具可读性:

import { EventEmitter } from 'events';

export default class extends EventEmitter {
  walk(event, cb, name) {
      console.log((name || 'creeper') + ' NOT listening for "' + event + "'");
      this.removeListener(event, cb);
  }

  // and so on
};