How to implement the Observer pattern?

  • 0
    I am trying to implement the observer pattern. Essence of the question:
    How to make the this.listeners variable in Observere one for everyone?
    Observer:
    export class Observer {
      constructor() {
        this.listeners = {}
      }
    
      trigger(event, ...args) {
        if (!Array.isArray(this.listeners[event])) {
          return false
        } 
        this.listeners[event].forEach(listener => {
          listener(...args)
        })
        return true
      }
    
      subscribe(event, fn) {
        this.listeners[event] = this.listeners[event] || []
        this.listeners[event].push(fn)
      }
    }


    Class Slider:
    export class Slider {
      constructor() {
        this.emitter = new Observer()
      }
    }


    In other classes, I inherit from Slider. Then I create objects of these classes, but when creating objects, apparently, each class has its own listeners variable.

    Class1:
    export class Model extends Slider {
      subscribe() {
        this.emitter.subscribe('1', (el) => console.log(el))
      }
    }


    Class2:
    class Index extends Slider {
      call() {
        this.emitter.trigger('1', '1')
      }
    }


    At the same time, in the subscribe method, in the Observer, I added a log to the listeners variable. When the subscribe method is executed on the Model, the listeners are updated. Then, when trigger is executed in index, an empty Listeners variable is passed to the observer.
    JavaScript David Hahn, Jul 4, 2019

  • 2 Answers
  • 0
    apparently, each class has its own listeners variable.


    That's all right.



    You either need to pass an argument to the constructor

    export class Slider {
    constructor(emitter) {
    this.emitter = emitter
    }
    }


    const obs = new Observer()
    const model = new Model(obs)
    const index = new Index(obs)




    Or implement a separate method

    const obs = new Observer()

    const model = new Model()
    model.attach(obs)

    const index = new Index()
    index.attach(obs)
    Anonymous

  • 0
    Hey.

    Please see here - & gt; https://refactoring.guru/en/design-patterns/observ ...



    If you are not writing this for educational purposes, I advise you to use a library that implements such functionality.

    https://rxjs-dev.firebaseapp.com/guide/overview
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!