Answer the question
In order to leave comments, you need to log in
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)
}
}
export class Slider {
constructor() {
this.emitter = new Observer()
}
}
export class Model extends Slider {
subscribe() {
this.emitter.subscribe('1', (el) => console.log(el))
}
}
class Index extends Slider {
call() {
this.emitter.trigger('1', '1')
}
}
Answer the question
In order to leave comments, you need to log in
SELECT DISTINCT dialogs.*
FROM dialogs LEFT JOIN messages ON dialogs.id = messages.id_dialog
ORDER BY messages.time ASC, dialogs.id ASC
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
apparently, each class has its own listeners variable.
export class Slider {
constructor(emitter) {
this.emitter = emitter
}
}
const obs = new Observer()
const model = new Model(obs)
const index = new Index(obs)
const obs = new Observer()
const model = new Model()
model.attach(obs)
const index = new Index()
index.attach(obs)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question