A
A
Alexey Golubev2020-10-27 10:26:35
MySQL
Alexey Golubev, 2020-10-27 10:26:35

How to implement the Observer pattern?

I'm trying to implement the "observer" pattern. The essence of the question:
How to make the this.listeners variable in Observere the same for all?
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 the trigger is executed on index, an empty Listeners variable comes to the observer.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Ilya, 2016-04-29
@rpsv

SELECT DISTINCT dialogs.* 
FROM dialogs LEFT JOIN messages ON dialogs.id = messages.id_dialog 
ORDER BY messages.time ASC, dialogs.id ASC

C
curator, 2016-04-29
@curator

SELECT
    dialogs.id,
    MAX(messages.created_at) AS createdAt
FROM
    dialogs
LEFT JOIN
    messages
    ON messages.dialog_id = dialogs.id
GROUP BY
    dialogs.id 
ORDER BY
    createdAt DESC

A
Alex, 2020-10-27
@Scket4

apparently, each class has its own listeners variable.

That's 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)

G
ggbb, 2020-10-27
@ggbb

Hello.
Please look here -> https://refactoring.guru/en/design-patterns/observ...
If you are writing this for educational purposes, I advise you to use a library that implements such functionality.
https://rxjs-dev.firebaseapp.com/guide/overview

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question