JavaScript/TypeScript 实现一个高效的事件监听派发类

本文介绍了Third类小三类第三方消息派发工具类,它不遵循监听顺序,演示了如何注册、监听、移除事件及派发事件,适用于项目中需要控制监听顺序的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Third

Description

Attention! Attention! Attention!
Note that this class does not maintain the order in which the message list listens
If A listens for the “show” event and B then listens for the “show” event, it will not show A and then show B, each time the event is removed
“Because the mistress does not abide by first come, first come!!”

If your project has multiple objects listening for an event and you care about the order in which the event is listened and dispatched, change the method “off” to use splice to remove events from the array.

案例 添加事件

  	//注册监听
    Third.on("message",this,this.message );
    Third.on("message",this,this.message2 );
    
    //注册监听一次
    Third.once("open",this,function(){
        
    });

    //移除指定
    Third.off("message",this,this.message );

    //移除 所有自身监听的message事件
    Third.off("message",this);

    //移除所有的message监听 
    Third.off("message");
    
    //移除所有this监听 所有事件
    Third.offall(this);

    //移除所有事件 清空事件池
    Third.offall();

    //派发时间 参数可变
    Third.do("message",1,false,"hello world");

API接口

public static on(event: string, caller: any, handl: Function): void //注册监听
public static once(event: string, caller: any, handl: Function): void //监听一次事件 回调会在第一时间被触发后删除自身
public static off(event: string, caller: any = undefined, handl: Function = undefined): void //移除监听
public static offall(caller: any = undefined) //移除所有监听
public static do(event: string, …params: any[]) //派发事件

源码

/*
 * @Description:  Third 小三类 第三方消息派发工具类
 * 
 * 注意!注意!注意!
 * 注意该类并不维护 消息列表监听的先后顺序   
 * 如果  A监听了 "show"事件  B接着监听了 "show"事件  并不会先 show A 再 show B, 每次事件移除的时候 
 * “因为小三是不遵守先来后到的!!! ”
 * 如果你的项目一个事件 有多个对象监听 并且很在意 监听和派发的顺序, 【 请修改 移除事件的方法 "off" 使用splice来移除数组中的事件 】
 * 
 * ============================================================================================================
 * 
 * attention! Attention! Attention!
 * Note that this class does not maintain the order in which the message list listens
 * If A listens for the "show" event and B then listens for the "show" event, it will not show A and then show B, each time the event is removed
 * "Because the mistress does not abide by first come, first come!!"
 *
 * If your project has multiple objects listening for an event and you care about the order in which the event is listened and dispatched, change the method "off" to use splice to remove events from the array.
 * 
 * 
 * @Autor: geek7
 * @Version: 1.0
 * @Date: 2022-02-11 16:07:51
 * @LastEditors: geek7
 * @LastEditTime: 2022-02-11 16:30:03
 */


export default class Third {

    private static _handls: {
        [key: string]: {
            caller: any,
            handl: Function,
            once?: boolean
        }[]
    } = {};


    /**
     * 监听事件
     * @param event 事件名称
     * @param caller 作用域
     * @param handl 回调方法
     */
    public static on(event: string, caller: any, handl: Function): void {

        if (undefined == Third._handls[event]) {

            Third._handls[event] = [{ caller, handl }];

        }
        else {

            Third._handls[event].push({ caller, handl });
        }
    }

    /**
     * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身
     * @param event 事件名称
     * @param caller 作用域
     * @param handl 回调方法
     */
    public static once(event: string, caller: any, handl: Function): void {
        if (undefined == Third._handls[event]) {

            Third._handls[event] = [{ caller, handl, once: true }];

        }
        else {

            Third._handls[event].push({ caller, handl, once: true });
        }
    }

    /**
     * 移除监听
     * @param event 事件名称
     * @param caller 作用域 如果忽略 则移除所有该事件的监听 off("show");//所有show事件相关监听都会被移除
     * @param handl 回调方法 如果忽略 则移除该事件列表里 所有caller相关的方法  off("show",this);// this作用域下所有对show的监听都会被移除
     */
    public static off(event: string, caller: any = undefined, handl: Function = undefined): void {

        //获取事件队列
        const list = Third._handls[event];

        //遍历所有事件
        if (list && list instanceof Array) {

            //移除所有当前事件的监听
            if (undefined == caller) {
                Third._handls[event] = [];
                return;
            }

            let e = null;
            for (let i = 0; i < list.length; i++) {

                e = list[i];

                //移除对应事件
                if (e.caller == caller && (undefined == handl || handl == e.handl)) {
                    //交换指针 移除尾部
                    list.splice(i--, 1);
                }
            }
        }
    }


    /**
     * 移除监听者的所有事件监听 
     * @param caller 监听者 如果为null 则进行clear   offall(); 事件池归零
     */
    public static offall(caller: any = undefined) {
        if (!caller) {

            Third._handls = {};
        }
        else {
            //遍历所有事件链表
            for (let k in Third._handls) {
                const list = Third._handls[k];
                if (list && list instanceof Array) {
                    for (let i = 0; i < list.length; i++) {
                        //移除对应事件
                        if (list[i].caller == caller) {
                            list.splice(i--, 1);
                        }
                    }
                }
            }
        }
    }

    /**
     * 派发事件
     * @param event 事件
     * @param params 可变参列表  do("show",true);   do("show",true,data);  do("show",data,true,"hello world",1234567890);
     */
    public static do(event: string, ...params: any[]) {

        const list = Third._handls[event];
        if (list && list instanceof Array) {

            let t = null;
            for (let i = 0; i < list.length; i++) {

                //触发回调
                t = list[i];
                t.handl.call(t.caller, ...params);

                //仅触发一次 则触发后移除
                if (t.once) {
                    list.splice(i--, 1);
                }
            }
        }

    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值