我尝试做一个简单的观察者模式。通知订餐者订餐。但执行时出现错误:TypeError:foodChanger.addEventListener不是函数
这是我的代码:
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));
您的foodChanger
变量是一个函数,因此不是具有EventTarget
方法的addEventListener
。