S
S
semennn2018-02-19 13:51:13
JavaScript
semennn, 2018-02-19 13:51:13

How to correctly implement a subscription in the Observer pattern?

Guys, tell me:
there is a primitive implementation of the Observer class (subscribe, publish methods).
and two classes: one publisher Main, another observer Slave.
How to correctly implement the pattern - an instance of the Main class subscribes listeners or an instance of Slave itself subscribes to events?
The first one is clear:

class Main extends Observer {
.............
}

let main = new Main(args);
let slave = new Slave(args);
main.subscribe(slave.func.bind(slave));

how is self-subscribing to main events implemented? or is everyone using publisher side subscription?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Litvinenko, 2018-02-19
@semennn

There are several solutions here, but most often I came across a solution similar to yours in the example, through the subscribe function
Either

main.events.on('.....', (e) => {
  .....
})

Y
Yuri Kostin, 2018-03-01
@yurakostin

In fact, there is one who publishes the news and one who wants to receive it.
Thus there are two entities: Publisher and Subscriber .
The publisher notifies that something has happened.
The subscriber responds to this incident. So we get
something like this:
methods:
props:
methods:

class Publisher {
    constructor() {
        this._subscribers = [];
        this._state = {};
    }

     get state() {
        return this._state;
    }

    set state(value) {
        this._state = Object.assign({}, this._state, value);
        // Неявный вызов, можно, наверное, сделать лучше
        this._notifySubscribers();
    }

    _notifySubscribers() {
        this._subscribers.forEach((subscriber) => subscriber.notify(this._state))
    }

    addSubscriber(subscriber) {
        this._subscribers.push(subscriber);
    }
}

class Subscriber {
    constructor(name) {
        this.name = name;
    }

    notify(state) {
        console.log(`${this.name}: i received a new data: `, state);
        console.log('\n\n')
    }
}

const publisher = new Publisher();
const subscriber1 = new Subscriber('John');
const subscriber2 = new Subscriber('Jane');
const subscriber3 = new Subscriber('Mary');

publisher.addSubscriber(subscriber1);
publisher.state = {a: 1};

publisher.addSubscriber(subscriber2);
publisher.state = {b: 2};

publisher.addSubscriber(subscriber3);
publisher.state = {c: 3};

Working code.
I hope that I did not deceive you anywhere and explained everything correctly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question