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

手写发布订阅 #875

Open
lgwebdream opened this issue Jul 6, 2020 · 2 comments
Open

手写发布订阅 #875

lgwebdream opened this issue Jul 6, 2020 · 2 comments
Labels
JavaScript teach_tag 头条 company 滴滴 company

Comments

@lgwebdream
Copy link
Owner

No description provided.

@lgwebdream lgwebdream added JavaScript teach_tag 头条 company 滴滴 company labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@GuoLizhi
Copy link

极简版Pub/Sub

    class Publisher {
        constructor() {
            this._subs = {}
        }
        addSub(type, callback) {
            if (!this._subs[type]) {
                this._subs[type] = []
            }
            this._subs[type].push(callback)
        }
        notify(type) {
            if (!this._subs[type]) return
            const args = Array.prototype.slice.call(arguments, 1)
            this._subs[type].forEach(callback => {
                callback.call(this, args)
            })
        }
        destory(type, func) {
            this._subs[type].forEach((item, index, arr) => {
                if (item === func) {
                    arr.splice(index, 1)
                }
            })
        }
        once(type, func) {
            function onceAdd() {
                func.apply(this, arguments)
                this.destory(type, onceAdd)
            }
            this.addSub(type, onceAdd)
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 头条 company 滴滴 company
Projects
None yet
Development

No branches or pull requests

2 participants