

export class eventManager {

    private static _instance: eventManager;
    private constructor() { }
    public static get instance(): eventManager {
        if (!this._instance) {
            this._instance = new eventManager();
        }
        return this._instance;
    }

    acList: any = {};

    on(ac: string | number, cb: Function, sender: any) {
        let arr = this.acList[ac];
        if (!arr) {
            arr = [];
            this.acList[ac] = arr;
        }

        // 避免重复添加
        for (let i in arr) {
            let item = arr[i];
            if (item.sender == sender) {
                return;
            }
        }

        let item: any = {};
        item.cb = cb;
        item.sender = sender;
        arr.push(item);
    }


    off(ac: string | number, cb: Function, sender: any) {
        let arr = this.acList[ac];
        if (!arr) {
            return;
        }

        let tmpArr = [];
        for (let i in arr) {
            let item = arr[i];
            if (item.cb == cb || item.sender == sender) {
                continue;
            }
            tmpArr.push(item);
        }

        this.acList[ac] = tmpArr;
    }

    send(ac: string | number, data?: any) {
        let arr = this.acList[ac];
        if (!arr) {
            return;
        }

        try {
            for (let i in arr) {
                let item = arr[i];
                let cb = item.cb;
                let sender = item.sender;
                let info = {
                    ac: ac,
                    data: data
                };
                cb.call(sender, info);
            }
        } catch (err) {
            console.log("eventManager send error:" + err.message, ac, data, err);
        }
    }
}

