xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js & Event Bus All In One

js & Event Bus All In One

global event handler (broadcast / trigger / emit / listen )

Event Emitter / Event Bus

// 实现一个 EventBus 类,这个类包含以下方法:
// on(监听事件,该事件可以被触发多次)
// once(也是监听事件,但只能被触发一次)
// fire(触发指定的事件)
// off(移除指定事件的某个回调方法或者所有回调方法)

// 解题思路: class 存储 evnets, 按类型分别处理 once


class EventBus {
    constructor() {
        this.eventBus = {};
    }
    on(name, callback) {
        this.eventBus[name] = {
            callback,
            once: false,
        };
    }
    once(name, callback) {
        this.eventBus[name] = {
            callback,
            once: true,
        };
    }
    off(name) {
        let keys = Object.keys(this.eventBus);
        if (keys.includes(name)) {
            delete this.eventBus[name];
        }
    }
    fire(name, person) {
        // dispatchEvent
        let keys = Object.keys(this.eventBus);
        if (keys.includes(name)) {
            let fun = this.eventBus[name].callback;
            let once = this.eventBus[name].once;
            // pass data
            fun(person);
            if (once) {
                delete this.eventBus[name];
            }
        }
    }
}


https://repl.it/@xgqfrms/Event-Bus

demo


const event = new EventBus();

const log = console.log;

event.on("drink", (person) => {
    log(person + "喝水");
});

event.on("eat", (person) => {
    log(person + "吃东西");
});

event.once("buy", (person) => {
    log(person + "买东西");
});

event.fire("drink", "我");
// 我喝水
event.fire("drink", "我");
// 我喝水
event.fire("eat", "其它人");
// 其它人吃东西
event.fire("eat", "其它人");
// 其它人吃东西
event.fire("buy", "其它人");
//其它人买东西
event.fire("buy", "其它人");
//这里不会再次触发buy事件,因为once只能触发一次

event.off("eat") //移除eat事件
event.fire("eat", "其它人");
//这里不会触发eat事件,因为已经移除了


refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-04-22 16:59  xgqfrms  阅读(301)  评论(1编辑  收藏  举报