如何将自定义事件添加到节点中的 类?

How do I add custom events to classes in node?

所以我只是选择节点,我想知道如何将自定义事件添加到 class。下面是我尝试的代码。本质上只是创建一个简单的农场 class,每当动物数量发生变化时,我都会显示新数字。我要创建的事件是 totalChanged。

let events = require('events');

class Farm{
    constructor(totalAnimals){
        this._totalAnimals = totalAnimals;
        events.EventEmitter.call(this);
    }

    get totalAnimals(){
        return this._totalAnimals
    }

    set totalAnimals(newTotal){
        this._totalAnimals = newTotal;
    }

    sellAnimals(amount){
        this._totalAnimals -= amount;
        this.emit("totalChanged");
    }

    buyAnimals(amount){
        this._totalAnimals += amount;
        this.emit("totalChanged");
    }

    toString(){
        return "Number of animals in farm: " + this._totalAnimals;
    }
}

let testFarm = new Farm(100);
testFarm.on("totalChanged",testFarm.toString());
testFarm.buyAnimals(20);

您有几个选择:

如果你想使用 instance.on 你必须 EventEmitter 继承 像这样:

let EventEmitter = require('events').EventEmitter

class Farm extends EventEmitter {
  constructor() {
    super()
  }

  buyAnimals() {
    this.emit('totalChanged', { value: 'foo' })
  }
}

let testFarm = new Farm()
testFarm.on('totalChanged', value => {
  console.log(value)
})

testFarm.buyAnimals()

如果您更喜欢使用 composition instead of inheritance,您可以简单地将 EventEmitter 实例化为 属性 并像这样使用 instance.eventEmitter.on

let EventEmitter = require('events').EventEmitter

class Farm {
  constructor() {
    this.eventEmitter = new EventEmitter()
  }

  buyAnimals() {
    this.eventEmitter.emit('totalChanged', { value: 'foo' })
  }
}

let testFarm = new Farm()
testFarm.eventEmitter.on('totalChanged', value => {
  console.log(value)
})

testFarm.buyAnimals()