Howdy Folks,
First of all, VERY happy to have typescript running instead of vanilla JavaScript!
I spent today converting my existing project and I was able to convert most of it, with one exception!
The Main Question
In typescript, how can you add an EventListener binding and utilise the registered SubClass of your type?
The Setup
In my version, I am combining event sheets and scripts. Might as well let the power of construct just do its thing!
So I have a timer on the Sheet, and that spawns the enemies, nice and simple.
My Level Controller class is setup and destroyed in and out of the level layouts, and in that we bind and unbind the instancecreate event, shown below. The EnemyControl script is the InstanceClass for all items under the Enemy family, and thus happily resolves the method call in the event callback (or explodes if i forgot to register the type, but oh well).
This is of course all managed through the sheer dark magic of javascript typeless making the objects function
Level Control Class
{
SetupLevel = () => {
this.runtime.objects.Enemy.addEventListener("instancecreate", this.SetupEnemy);
}
Teardown = () => {
this.runtime.objects.Enemy.removeEventListener("instancecreate", this.SetupEnemy);
};
SetupEnemy = (e) => e.Setup(this);
}
The Enemy Subclass
export default class EnemyControl extends ISpriteInstance
{
constructor(){...}
setup(levelControl){
this.OnArrive = levelControl.OnEnemyArrive;
this.OnKilled = levelControl.OnEnemyKilled;
}
}
The Problem
And now to Typescript, and the same event handler code looks something like
SetupEnemy = (e: ObjectClassInstanceCreateEvent<InstanceType.Enemy>) => e.instance.setup(this);
However, the PROBLEM is that of course the Enemy Instance Type does NOT have the extended functionality of the EnemyControl subclass, and so fails to compile
Changing the event to be the <EnemyControl> type of course makes the callback binding fail because it doesn't match the signature required
SO I am somewhat stuck
Brainstorming Solutions
I have only come up with about two options
- Move my Tower Controller class into a Global access scope and then just utilise it in the constructor of EnemyControl
- change the <T> on the event to be any -
SetupEnemy = (e: ObjectClassInstanceCreateEvent<any>) => e.instance.setup(this);
This at least does not appear to give me errors on compile!
I am fairly certain that the <any> will work, as really that falls back to older javascript processing, I just cant say I like it. But I hate it less than the globaling.....
Any ideas or things I missed please let me know!