繁体   English   中英

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

[英]Can't understand what's going on with EventEmitter using webpack and es6 modules

我试图同时学习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

这只是dVpEe.prototype.hear的错字。

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

我还建议将不赞成使用的 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
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM