【问题标题】:observer pattern with changing function具有变化功能的观察者模式
【发布时间】:2020-05-20 14:56:05
【问题描述】:

我尝试做一个简单的观察者模式。通知订户换餐。但在执行时出现错误: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));

【问题讨论】:

    标签: javascript observer-pattern


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2011-09-25
      • 2016-02-20
      • 2023-04-10
      • 2023-03-06
      • 1970-01-01
      • 2022-12-14
      相关资源
      最近更新 更多