i try to do a simple observer pattern. which informs subscribers of a meal change. but at execution I get an error: TypeError: foodChanger.addEventListener is not a function
this is my code:
class EventObserver {
constructor() {
this.observers = [];
}
subscribe(fn) {
this.observers.push(fn);
}
unsubscribe(fn) {
this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}
broadcast(data) {
this.observers.forEach((subscriber) => subscriber(data));
}
}
const food = 'fruit'
const blogObserver = new EventObserver();
blogObserver.subscribe(() => {
food.uptade(this);
});
const foodChanger = function () {
const foods = ['vegetable', 'pizza', 'salad'];
const timeSpin = setInterval(()=>{this.food = foods[Math.floor(Math.random()*foods.length)];
},200);
setTimeout(() => {
clearInterval(timeSpin)
}, 2000);
}
foodChanger.addEventListener('keyup', () => blogObserver.broadcast(foodChanger));
Your foodChanger
variable is a function and therefore not an EventTarget
that has the addEventListener
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.