Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

观察者模式 / 发布订阅 #24

Open
ZhangHanwen96 opened this issue Mar 15, 2021 · 0 comments
Open

观察者模式 / 发布订阅 #24

ZhangHanwen96 opened this issue Mar 15, 2021 · 0 comments

Comments

@ZhangHanwen96
Copy link
Owner

ZhangHanwen96 commented Mar 15, 2021

订阅发布模式

// 订阅发布模式
var events = (function(){
    var topics = {};

    return {
        subscribe: function(topic, handler) {
            if(!topics.hasOwnProperty(topic)) {
                topics[topic] = [];
            }
            topics[topic].push(handler);
        },

        public: function(topic, info) {
            if(topics.hasOwnProperty(topic)) {
                topics[topic].forEach(handler => handler(info));
            }
        },

         unsubscribe: function(topic, handler) {
            if(!topics.hasOwnProperty(topic)) return;

            topics[topic] = topics[topic].filter(item => item !== handler);
        },

        removeAll: function(topic) {
            if(topics.hasOwnProperty(topic)) {
                topics[topic] = [];
            }
        }
    }
})()

观察者

class Observer {
    constructor(name) {
        this.name = name
    }

    update(value) {
        console.log(`${this.name} has recived message from subject + ${value}`)
    }
}

class ObserverList {
    constructor() {
        this.observerList = []
    }

    add(ob) {
        return this.observerList.push(ob);
    }

    remove(ob) {
        this.observerList.filter(observer => ob != observer);
    }

    getList() {
        return this.observerList;
    }
}

class Subject {
    constructor() {
        this.observers = new ObserverList();
    }

    addObserver(ob) {
        this.observers.add(ob);
    }

    removeObserver(ob) {
        this.observers.remove(ob);
    }

    notify(...args) {
        for(let ob of this.observers.getList()) {
            ob.update(...args)
        } 
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant