define

The observer pattern defines a one-to-many dependency between objects, where all dependent objects are notified when an object’s state changes. — JavaScript Design Patterns and Development Practices

Applicable scenario

1. Asynchronous programming.

2. Bidirectional data binding of MVVM.

3. Communication between modules.

Implementation examples

// Implement an event center
class EventCentre {
    constructor () {
        this._cache = {};
    }
    on(eventName = ' ', fn = () => {}) {
        const cache = this._cache;
        cache[eventName] ? cache[eventName].push(fn) : (cache[eventName] = [fn]);
    }
    emit(eventName = ' ') {
        const fnList = this._cache[eventName];
        if(! fnList) {return;
        }
        fnList.forEach(fn= > { fn(); });
    }
    off(eventName = ' ', fn) {
        const f = fn ? this._offOne : this._offAll;
        f.call(this, eventName, fn);
    }
    _offAll(eventName = ' ') {
        this._cache[eventName] = [];
    }
    _offOne(eventName = ' ', fn) {
        const fnList = this._cache[eventName];
        const index = fnList.findIndex(f= > f === fn);
        fnList.splice(index, 1);
    }
    once(eventName = ' ', fn = () => {}) {
        this.on(eventName, () = > {
            fn();
            this.off(eventName, fn); }); }}// Test examples
const TEST_EVENT = 'test';
const eventCentre = new EventCentre();

const func1 = () = > {
    console.log('on 1! ');
}

eventCentre.on(TEST_EVENT, func1);
eventCentre.on(TEST_EVENT, () = > {
    console.log('on 2! ');
});
eventCentre.on(TEST_EVENT, () = > {
    console.log('on 3! ');
});

eventCentre.once(TEST_EVENT, () = > {
    console.log('once! ');
});

/ / test once
console.log('------- test once -------');
eventCentre.emit(TEST_EVENT); 
eventCentre.emit(TEST_EVENT);

/ / test offOne
console.log('------- test off one -------');
eventCentre.off(TEST_EVENT, func1);
eventCentre.emit(TEST_EVENT);

/ / test offAll
console.log('------- test off all -------');
eventCentre.off(TEST_EVENT);
eventCentre.emit(TEST_EVENT);
Copy the code

The result is as follows