So I'm just picking up node and I'm wondering how do I add custom events to a class. Code below of my attempt. Essentially just creating a simple farm class, and every time the number of animals change, I display the new number. The event I'm trying to create is 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);