We can inherit from event then our class can emit event here is example:
const EventEmitter = require('events')
class Tank extends EventEmitter {
FulledTill = 0
maxCapacity = 50
constructor(maxCapacity = 50) {
super()
this.maxCapacity = maxCapacity
}
addWater(addedAmount, listener) {
console.log("MaxCapacity",this.maxCapacity)
this.FulledTill = addedAmount + this.FulledTill
if (addedAmount + this.FulledTill > this.maxCapacity) {
this.emit("tankFull")
}
}
removeWater(removedAmount) {
console.log("MaxCapacity",this.maxCapacity)
this.FulledTill = this.FulledTill - removedAmount
if (this.FulledTill - removedAmount < 0) {
this.emit("tankEmpty")
}
}
}
function tankFullListener() {
console.log("Tank is Overflowing")
}
function tankEmptyListener() {
console.log("Tank is Empty")
}
var tank = new Tank(30)
tank.addListener("tankFull", tankFullListener)
tank.addListener("tankEmpty", tankEmptyListener)
tank.addWater(60)
tank.removeWater(60)
Output:
MaxCapacity 30
Tank is Overflowing
MaxCapacity 30
Tank is Empty
No comments:
Post a Comment