繁体   English   中英

观察者模式与改变 function

[英]observer pattern with changing function

我尝试做一个简单的观察者模式。 通知订户换餐。 但在执行时出现错误:TypeError: foodChanger.addEventListener is not a function

这是我的代码:

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变量是 function,因此不是具有addEventListener方法的EventTarget

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM