具有更改功能的观察者模式

问题描述 投票:1回答:1

我尝试做一个简单的观察者模式。通知订餐者订餐。但执行时出现错误: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));
javascript observer-pattern
1个回答
0
投票

您的foodChanger变量是一个函数,因此不是具有EventTarget方法的addEventListener

© www.soinside.com 2019 - 2024. All rights reserved.