Reputation: 59
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);
Upvotes: 4
Views: 2269
Reputation: 22949
You've got a couple options:
If you want to use instance.on
you have to inherit from EventEmitter
like so:
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()
If you prefer to use composition instead of inheritance, you can simply instantiate EventEmitter
as a property and use instance.eventEmitter.on
like so:
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()
Upvotes: 13