ts 事件派发


class EventDispatcher
{
    /**事件列表*/
    private static eventList = {};

    constructor()
    {
       
    }

    /** 
     * 派发事件
     * @param type 事件类型
     * @param args 事件参数
     */
    public static dispatchEvent(type:string, ...args:any[]):void
    {
        let arr:Array<any> = this.eventList[type];
        if(arr)
        {
            arr.forEach(element => 
            {
                element[0].apply(element[1], args);
                // listener.call(thisObject, args);
            });
        }
    }

    /**
     * 监听事件
     * @param type       事件类型
     * @param listener   回调函数
     * @param thisObject 回调执行对象
     */
    public static addEventListener(type:string, listener:Function, thisObject:any):void
    {
        let arr:Array<any> = this.eventList[type];
        if(!arr)
        {
            arr = [];
            this.eventList[type] = arr;
        }
        else
        {
            arr.forEach(element => 
            {
                if(element[0] == listener && element[1] == thisObject)
                {
                    return;
                }
            });
        }
        arr.push([listener, thisObject]);
    }

    /**
     * 移除事件
     * @param type       事件类型
     * @param listener   回调函数
     * @param thisObject 回调执行对象
     */
    public static removeEventListener(type:string, listener:Function, thisObject:any):void
    {
        var arr:Array<any> = this.eventList[type];
        if(arr)
        {
            var len = arr.length;
            for(var i = len - 1; i >= 0; i--)
            {
                if(arr[i][0] == listener && arr[i][1] == thisObject)
                {
                    arr.splice(i, 1);
                }
            }
        }
        if(arr && arr.length == 0)
        {
            this.eventList[type] = null;
            delete this.eventList[type];
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM