兄dei,来封装一个自定义事件玩玩

593 阅读1分钟

如题,

很多面试官应该都喜欢问这个问题吧,其实很简单,虽然实现很简单,

但也可谓是观察者模式的体现吧,废话不多说,直接上代码吧。


你站着先别动,我先去写几行代码。


                                              ——朱自清,没说过

  

const CustomEvent = {
    depot: {onceEvent: []},
    on(eventName, callback) {
        if (!this.depot[eventName]) {
            this.depot[eventName] = [];
        }
        this.depot[eventName].push(callback);
    },
    once(eventName, callback) {
        if (!this.depot[eventName]) {
            this.depot[eventName] = [];
        }
        this.depot[eventName] = [callback];
        if (!this.depot.onceEvent.includes(eventName)) {
            this.depot.onceEvent.push(eventName);
        }
    },
    off(eventName) {
        if (this.depot[eventName]) {
            delete this.depot[eventName];
            let {onceEvent = []} = this.depot;
            this.depot.onceEvent = onceEvent.filter(v => v !== eventName);
            console.log(`%c移除自定义事件:${eventName}!`, "color:white;background:red;");
        }
    },
    emit(eventName, arg) {
        const cbs = this.depot[eventName];
        if (cbs && cbs.length > 0) {
            console.log(`%c触发自定义事件:${eventName}!`, "color:white;background:green;");
            for (let i = 0; i < cbs.length; i++) {
                typeof cbs[i] === "function" && cbs[i](arg);
            }
            if (this.depot.onceEvent.includes(eventName)) {
                this.off.bind(this, eventName)();
            }
        }
    }
};

         代码很简单,就不啰嗦了,

没事,走两步。。。。。

CustomEvent.on("customEvent1", data => {
    console.log("执行了customEvent1的回调", "data=", data);
});
CustomEvent.on("customEvent2", data => {
    console.log("执行了customEvent2的回调", "data=", data);
});
CustomEvent.on("customEvent3", data => {
    console.log("执行了customEvent3的回调", "data=", data);
});
CustomEvent.once("customEvent-Once", data => {
    console.log("执行了customEvent-Once", "data=", data);
});
CustomEvent.off("customEvent2");
CustomEvent.emit("customEvent1", "你好呀customEvent1");
CustomEvent.emit("customEvent2", "你好呀customEvent2");
CustomEvent.emit("customEvent3", "初次见面,你好呀customEvent3");
CustomEvent.emit("customEvent3", "你好呀customEvent3,又见到你了");
CustomEvent.emit("customEvent-Once", "customEvent-Once么么哒~~");
CustomEvent.emit("customEvent-Once", "customEvent-Once么么哒2~~");

       看看输出结果