egret鍵盤pc端事件監聽


最近看egret沒有監聽鍵盤事件的方法,就自己寫了一個


使用比較簡單,只有兩個公共方法:

addListener//添加監聽

removeListener//移出監聽


class PcKeyBoardHelper {
    private static _instance: PcKeyBoardHelper;
    private list: Object;
    private isListening: boolean = false;

    public constructor() {
        this.list = {};
    }

    public static get instance(): PcKeyBoardHelper {
        if(PcKeyBoardHelper._instance == null) {
            PcKeyBoardHelper._instance = new PcKeyBoardHelper();
        }
        return PcKeyBoardHelper._instance;
    }

    private add(): void {
        if(this.isListening == false) {
            this.isListening = true;
            document.addEventListener("keydown",PcKeyBoardHelper.instance.onKeyDown);
        }
    }

    private onKeyDown(evt): void {
        console.log("evt.keyCode:" + evt.keyCode);
        var target: any;
        for(target in PcKeyBoardHelper.instance.list) {
            var vo: KeyVo = PcKeyBoardHelper.instance.list[target];
            vo.callback.call(vo.target,evt);
        }
    }


    /**
     * 注冊監聽
     * @param callback 回調方法
     * @param target 
     */
    public addListener(callback: any,target: any): void {
        var temp: string = egret.getQualifiedClassName(target);
        if(PcKeyBoardHelper._instance.list[temp] == null) {
            var vo: KeyVo = new KeyVo(temp,target,callback);
            PcKeyBoardHelper._instance.list[vo.name] = vo;
        }
        PcKeyBoardHelper._instance.add();
    }


    /**
     * 移出監聽
     */
    public removeListener(target: any): void {
        var temp: string = egret.getQualifiedClassName(target);
        if(PcKeyBoardHelper._instance.list[temp] != null) {
            delete PcKeyBoardHelper._instance.list[temp];
        }
        this.checkCount();
    }


    private checkCount(): void {
        for(var key in PcKeyBoardHelper._instance.list) {
            return;
        }
        document.removeEventListener("keydown",PcKeyBoardHelper.instance.onKeyDown);
        this.isListening = false;
    }
}

class KeyVo {
    public name: string = "";
    public target: egret.DisplayObject;
    public callback: Function;

    public constructor(name: string,tar: any,call: any) {
        this.name = name;
        this.target = tar;
        this.callback = call;
    }
}

其中KeyVo類不是必須的,應該優化一下~~

注意!

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



 
粤ICP备14056181号  © 2014-2021 ITdaan.com