egret.IEventDispatcher 使用範例
class Main extends eui.UILayer {
protected createChildren(): void {
super.createChildren();
egret.lifecycle.onPause = () => egret.ticker.pause();
egret.lifecycle.onResume = () => egret.ticker.resume();
egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
this.runGame();
}
private async loadResource() {
let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
await RES.loadConfig('resource/default.res.json', 'resource/');
await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
await RES.loadGroup('preload', 0, loadingView);
this.stage.removeChild(loadingView);
}
private async runGame() {
await this.loadResource();
// --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---
const myCaller = new LimitCaller(3); // 只能觸發3次事件的限制觸發器
myCaller.addEventListener(LimitCaller.CALL, () => console.log(myCaller.callTimes), this);
myCaller.dispatchEvent(new egret.Event(LimitCaller.CALL)); // 1
myCaller.dispatchEvent(new egret.Event(LimitCaller.CALL)); // 2
myCaller.dispatchEvent(new egret.Event(LimitCaller.CALL)); // 3
myCaller.dispatchEvent(new egret.Event(LimitCaller.CALL)); // 不會再觸發
myCaller.reset(); // 觸發次數歸0
myCaller.dispatchEvent(new egret.Event(LimitCaller.CALL)); // 1
}
}
// 遵循 egret.IEventDispatcher 介面要求實作方法
class LimitCaller extends egret.HashObject implements egret.IEventDispatcher {
public static readonly CALL: string = 'call';
private dispatcher: egret.EventDispatcher;
private _callTimes: number = 0;
private limit: number;
public get callTimes(): number {
return this._callTimes;
}
public reset(): void {
this._callTimes = 0;
}
public constructor(limit: number) {
super();
this.dispatcher = new egret.EventDispatcher(this);
this.limit = limit;
}
public once(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number): void {
this.dispatcher.once(type, listener, thisObject, useCapture, priority);
}
public addEventListener(type: string, listener: Function, thisObject: any,
useCapture: boolean = false, priority: number = 0): void {
this.dispatcher.addEventListener(type, listener, thisObject, useCapture, priority);
}
public dispatchEvent(evt: egret.Event): boolean {
if (++this._callTimes > this.limit) return false;
return this.dispatcher.dispatchEvent(evt);
}
public hasEventListener(type: string): boolean {
return this.dispatcher.hasEventListener(type);
}
public removeEventListener(type: string, listener: Function, useCapture: boolean = false): void {
this.dispatcher.removeEventListener(type, listener, useCapture);
}
public willTrigger(type: string): boolean {
return this.dispatcher.willTrigger(type);
}
}
沒有留言:
張貼留言