4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptでEventDispatcherを作る

Last updated at Posted at 2013-08-14

TypeScriptの勉強がてらよく使うクラスを実装してみた。

interface ICustomEvent {
	type:string;
	data:Object;
	timeStamp:number;
	defaultPrevented:boolean;
}

class CustomEvent implements ICustomEvent {
	data:Object;
	timeStamp:number;
	defaultPrevented:boolean = false;
	constructor (public type:string) {
		this.timeStamp = new Date().valueOf();
	}
	preventDefault () {
		this.defaultPrevented = true;
	}
}

interface IEventListenerList {
	[index:string]:(e:Event) => any;
}

interface IEventDispatcher {
	on(type:string, listener:(e:Event) => any):void;
	off(type:string, listener:Function):void;
	trigger(type:string, data:Object):boolean;
}

class EventDispacther implements IEventDispatcher {
	private _listeners:IEventListenerList = {};
	on (types:string, listener:(e:Event) => any):void {
		var typeList:string[] = types.split(/\s+/);
		var i:number = 0;
		var l:number = typeList.length;
		for (; i < l; i++) {
			this._listeners[typeList[i]] = listener;
		}
	}
	off(types:string, listener?:Function):void {
		var typeList:string[] = types.split(/\s+/);
		var i:number = 0;
		var l:number = typeList.length;
		var type:string;
		for (; i < l; i++) {
			type = typeList[i];
			if (listener == null || this._listeners[type] === listener) {
				delete this._listeners[type];
			}
		}
	}
	trigger(type:string, data:Object = {}, context:any = this):boolean {
		var listener:Function;
		if (listener = this._listeners[type]) {
			var e:CustomEvent = new CustomEvent(type);
			e.data = data;
			listener.call(context, e);
			return !e.defaultPrevented;
		}
		return true;
	}
}

Javaや(本格的な)ActionScript3未経験な僕とってinterfaceの実装というか概念がこれであってるのかあやふや。

listenerの第一引数をEvent型にしてるのに、実際渡すものはCustomEvent型でもコンパイル通るあたり、これでいいのかよくわっていない。


IEventListenerList というinterfaceを作って、シグニチャの代わりみたいに扱っているけど、これもこれで使い方があってるのか疑問…。


まだまだよくわっておりません!

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?