Implement observer mode - observer

Keywords: Javascript

observer mode

In our daily development and use, we often encounter some scenarios that need to use observer mode. For example, if we log in successfully, we need to change the information of multiple modules of the synchronization page. At this time, the best choice is to use observer mode.
It's another unforgettable Qingming Festival. This time, I had to write on the bus. From 9:30 last night at Guangzhou bus station to 12:30 at noon, I haven't arrived yet. After 15 hours, I haven't got home. It's not that my hometown is too far away, but that there are too many rich families in China, which leads to traffic jams all the way. I think a lot of little friends have the same feeling, but it's more than an hour before they get home.

class Apm {
    constructor(){
        //Observer mode
        this.observer = {
            //Subscribe
            addSubscriber: function (callback, opt) {
                this.subscribers[this.subscribers.length] = {
                    callback: callback,
                    opt: (opt !== 'undefined') ? opt : {}
                };
            },
            //Unsubscribe
            removeSubscriber: function (callback) {
                for (var i = 0; i < this.subscribers.length; i++) {
                    if (this.subscribers[i].callback === callback) {
                        delete (this.subscribers[i]);
                    }
                }
            },
            //Release
            publish: function (what, _observer) {
                for (var i = 0; i < this.subscribers.length; i++) {
                    if (typeof this.subscribers[i].callback === 'function') {
                        
                        let observer = (_observer !== 'undefined') ? _observer : {};
                        // Perform various callbacks of registration
                        this.subscribers[i].callback({ret: what, opt: this.subscribers[i].opt, observer: observer});
                    }
                }
            },
            // Object o has observer function
            make: function (o) { 
                for (var i in this) {
                    o[i] = this[i];
                    o.subscribers = [];
                }
            }
        };
        this.observerLogin = {
            success: function (ret) {
                this.publish(ret, {type: 'success'});
            },
            error: function(ret){
                this.publish(ret, {type: 'error'});
            }
        };
        this.observer.make(this.observerLogin);
    }
}

Posted by liljester on Sat, 30 Nov 2019 02:31:23 -0800