I have a generic type that will be the base class for events in an Event system. We expect these to be singletons but it also is generic so that subclasses can specify the type of the argument they expect in the callback when the event fires.
What I have looks something like this:
export interface IEvent { }
export interfact IEventArg { }
export abstract class Event<TEvent extends IEvent, TEventArg extends IEventArg> implements IMessageHandler {
private static s_instance : any;
private static s_isInitializing : boolean;
constructor() {
if (!Event.s_isInitializing)
throw new Error ("Use the GetInstance method to get this class instance.");
}
public static GetInstance<TEvent extends IEvent, TEventArg extends IEventArg>(type: { new() : T; }) : TEvent {
if (!s_instance) {
s_isInitializing = true;
s_instance = new type();
s_isInitializing = false;
}
return s_instance;
}
}
export class SelectionEvent extends Event<SelectionEvent, EmptyEventArg> {
...
}
var event = SelectionEvent.GetInstance(SelectionEvent);
There are some things in here I consider odd and are there mostly because of Typescript language requirements. The argument to GetInstance seems to be necessary because var x = new TEvent()
seems to not be allowed by TypeScript. The empty interfaces help enforce what can be accepted as generic types.
What does not seem to work here is the combination of static variables and generic types. The block within the GetInstance method is what i WANT to do but obviously it does not compile. I'm also concerned that the static instance variable will not be created once per Event but rather just once per Event instance and will thus be overwritten.
Any guidance here would be much appreciated.
Aucun commentaire:
Enregistrer un commentaire