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