directory

  1. Observer model
  2. Observer model-brain map analysis
  3. reference
  4. conclusion
  5. scenario
  6. The difference between the observer model and the subscription publishing model

Note: For subsequent examples, Aclass is the target object and Bclass is the observer

I. Observer model

The observer pattern is more coupled than the publish-subscribe pattern and is often used to achieve some responsive effects. In the Observer mode, there are only two subjects, the target object Subject and the Observer Observer.

  • Observers need to beObserverIn order to achieveupdateMethod to be called by the target object.updateMethod to execute custom business code.
  • The target objectSubjectAlso known as the observed or the subject, it has a very simple function, it can be understood as managing only one kind of event.SubjectYou need to maintain your own array of observersobserverListWhen itself changes, by calling itsnotifyMethod, telling each observer in turn to executeupdateMethods.

With this definition, we can implement a simple version of the observer pattern.

/ / observer
class Observer {
    /** * constructor *@param {Function} Cb callback function that executes */ when receiving a notification from the target object
    constructor(cb){
        if (typeof cb === 'function') {
            this.cb = cb
        } else {
            throw new Error('Observer constructor must pass function type! ')}}/** * execute */ when notified by the target object
    update() {
        console.log('Observer update'.'this.cb'.this.cb.toString());
        this.cb()
    }
}

// Observe (target object)
class Subject {
    constructor() {
        // Maintain observer list 'Aclass' stored in [Bclass, Bclass, Bclass... `
        this.observerList = [];
        
    }
    /** * Add an observer 'aclass.add (Bclass)' *@param {Observer} Observer Observer instance */
    addObserver(observer) {
        console.log('Add an observer addObserver',observer);
        this.observerList.push(observer);
        console.log('maintain observerList this.observerlist'.this.observerList);
    }
    /** * Notify all observers' aclass. notify '->' bcalss. update '->' bcalss.cb '*/
    notify() {
        this.observerList.forEach(observer= > {
            console.log('Subject notify');
            observer.update()
        })
    }
}

const observerCallback = function() {
    console.log('observerCallback I've been notified ')}const observer = new Observer(observerCallback)
console.log('the observer instance', observer);
const subject = new Subject();
console.log('the subject instance', subject);
subject.addObserver(observer);
subject.notify();

Copy the code

2. Observer model-brain map analysis

1) Observer class

2) Observed class (target object)

3) Instantiate the call

3) Invoke the process

// Declare two observer callbacks, which are the final functions to execute
var observerCb1 = function() {
    console.log('observer Cb1')}var observerCb2 = function() {
    console.log('observer Cb2')}// Instantiate two observers
var observer1 = new Observer(observerCb1)
var observer2 = new Observer(observerCb2)

// Instantiate the target object
const subject = new Subject();

// Add an observer instance to the target object
subject.addObserver(observer1);
subject.addObserver(observer2);
// Notify all observers to invoke their observer callback
subject.notify();

// Final output
// observer Cb1
// observer Cb2
Copy the code

4) Call the procedure

5) Red is the key call

Three, reference

  • Observer model

Four,

  • Observer mode calls the observer callbacks defined on the outside

  • The key is to pass observer instances to the instantiated target object, so that the instantiated target object has all the attributes and methods of the observer and can call their own externally defined observer callbacks.

  • Observer mode: The target object’s constructor array holds all observer instances.

  • The target object, which is an instance of the observed class, can add an instance of another class ** -> maintain a list of observer instances by itself -> call the update method on each observer instance prototype -> thus indirectly calling the incoming observer callback stored on the observer instance

  • An instance of a class can add an instance of another class and store it, calling an argument passed in by another class (the observer callback is the CB stored in its constructor).

  • For example: Aclass is the target object and Bclass is the observer

  • Aclass.add(Bclass)

  • Aclass.notify() actually calls bclass.prototype. update Update calls cb in the Bclass constructor, which is the observer callback passed in.

  • Instantiated class A class B is added to the class A list of observers in the array: Aclass. Add (Bclass) – > Aclass. Prototype. ObserverList = [{cb: () = > {‘ final to perform observer callback ‘}, update: fn}, {cb: () = > {‘ final to perform observer callback ‘}, update: fn},… -> Acalss notifies all observers in the list of observers -> bclass.cb () to call callback on the observer

  • Aclass.add(Bclass) -> Aclass [Bclass, Bclass, Bclass… -> Aclass.notify -> Bcalss.update -> Bcalss.cb

  • Observer instances and observer instance callbacks are ready -> the target object adds these observer instances to the observer list -> the target object at some point iterates through all the observer callbacks passed in to the observer instance

  • Attached is the original brain map

www.processon.com/view/link/6… www.processon.com/diagraming/…

Five, the scene

1) Data response formula of Vue2

Dependency collection: Get maintains a DEP array for each property on data that holds all observer instances. Update data to view update: When data changes, set calls notify on the target object, iterates through all the observers in the list of observers on the target object, and calls the observer callbacks on the observer instance.

2) Browser events listen for addEventLister

The difference between the observer model and the subscription publishing model

Remember a key point

This. ObserverList = [Bclass, Bclass, Bclass…]

The Observer pattern is implemented by two classes. One observer class, one target object class. The target object class instance adds the observer class instance, then notifies notify, iterating through all the observer callbacks stored in the target object array.

{‘ event A ‘: [cb1, CB2,cb3…] , ‘event B ‘: [cb1, CB2, CB3… . }

Subscription publishing is a class to implement. The constructor of a class stores an object that stores events and their corresponding callbacks. Then, on the prototype, you have subscribed to events on(events, callbacks), fired events emit(events), fired once events once(events), and deleted events off(events).

The Observer pattern is implemented by two classes, and the subscription publishing pattern is implemented by one class

Observer mode is a one-to-many relationship, and the two classes are coupled.

[Subscription publishing mode] you subscribe to your events, I publish mine. Each other. You just subscribe and you don’t need to follow. Any subsequent published event is triggered. Then you can receive it.

[Subscription publishing mode] scenario, wechat public number.