手写EventBus自定义事件

文章介绍了一个简单的EventBus类,用于处理事件监听和发布。EventBus提供了on方法来添加事件监听器,once方法用于添加只执行一次的监听器,off方法用于移除监听器,而emit方法则用于触发事件。此外,还展示了如何模拟JavaScript的bind方法。
摘要由CSDN通过智能技术生成
export default class EventBus {
    constructor() {
        this.events = {};
    }
    on(type, fn, isOnce = false) {
        const events = this.events;
        if (events[type] == null) {
            events[type] = []; // 初始化 key 的 fn 数组
        }
        events[type].push({ fn, isOnce });
    }
    once(type, fn) {
        this.on(type, fn, true);
    }
    off(type, fn) {
        if (!fn) {
            // 解绑所有 type 的函数
            this.events[type] = [];
        }
        else {
            // 解绑单个 fn
            const fnList = this.events[type];
            if (fnList) {
                this.events[type] = fnList.filter(item => item.fn !== fn);
            }
        }
    }
    emit(type, ...args) {
        const fnList = this.events[type];
        if (fnList == null)
            return;
        // 注意
        this.events[type] = fnList.filter(item => {
            const { fn, isOnce } = item;
            fn(...args);
            // once 执行一次就要被过滤掉
            if (!isOnce)
                return true;
            return false;
        });
    }
}
const e = new EventBus();
function fn1(a, b) { console.log('fn1', a, b); }
function fn2(a, b) { console.log('fn2', a, b); }
function fn3(a, b) { console.log('fn3', a, b); }
e.on('key1', fn1);
e.on('key1', fn2);
e.once('key1', fn3);
e.on('xxxxxx', fn3);
e.emit('key1', 10, 20); // 触发 fn1 fn2 fn3
e.off('key1', fn1);
e.emit('key1', 100, 200); // 触发 fn2

bind暂存

// 模拟 bind
Function.prototype.bind1 = function () {
    // 将参数拆解为数组
    const args = Array.prototype.slice.call(arguments)

    // 获取 this(数组第一项)
    const t = args.shift()

    // fn1.bind(...) 中的 fn1
    const self = this

    // 返回一个函数
    return function () {
        return self.apply(t, args)
    }
}

function fn1(a, b, c) {
    console.log('this', this)
    console.log(a, b, c)
    return 'this is fn1'
}

const fn2 = fn1.bind1({x: 100}, 10, 20, 30)
const res = fn2()
console.log(res)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值