【问题标题】:How do I add custom events to classes in node?如何将自定义事件添加到节点中的类?
【发布时间】:2019-11-29 07:38:47
【问题描述】:

所以我只是拿起节点,我想知道如何将自定义事件添加到类中。下面是我尝试的代码。本质上只是创建一个简单的农场类,每次动物数量发生变化时,我都会显示新的数字。我尝试创建的事件是 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);

【问题讨论】:

    标签: javascript node.js class events custom-events


    【解决方案1】:

    你有几个选择:

    如果您想使用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()
    

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 2019-10-24
      • 1970-01-01
      • 2021-05-21
      • 2012-02-11
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多