简体   繁体   中英

How to correctly use Typescript extended classes with Phaser

I am new to both Javascript and Typescript. I've written a simple Phaser game in Javascript and now want to re-write it in Typescript ES2015 (ES6).
I have extended the Phaser.Game class such that it is passed a variable through it's constructor. This is used to create a websocket. This socket could exist as a property of the Game or State types (I show this in the example).
I've extended the Phaser.State class to include the property that needs to be set by the websocket data through the websocket's .onmessage member function.

I've shown the createWebsocket as a function just for completeness, in reality it's a member function of one of the classes.

function createWebsocket(wsPath, callback){
    var ws = new WebSocket(wxPath);
    ws.onmessage = callback;
    return ws;
}

export class Game extends Phaser.Game {
    csocket: WebSocket;
    constructor(wsPath, container) {
    this.state.add('Boot', Boot, false);
    this.csocket = createWebsocket(wsPath, this.handleMsg);
}

export class Boot extends Phaser.State {
    csocket: WebSocket;
    constructor(){super();}
    my_value: number;
    setMyValue(value) {this.my_value = value};
    this.csocket = createWebsocket(wsPath, this.handleMsg);
}

How do I either pass data from the extended Game class instance to the Boot instance or access the createWebsocket member function of the Boot instance?

If I use the following in Game;

state = this.state.getCurrentState();
state.setValue()

I get a (trans)compiler error as getCurrentState() returns the instance of the base class not the extended class even though the extended class type is passed to the state.add function

I see no way to pass the wsPath to the constructor for the Boot class as a type is passed to the .add function.

The simple answers are always the best ones. So, answering my own question......

Though the examples don't clearly show this, the this.state.add call does not just allow a class, it also allows a class instance. Just use new.

export class Game extends Phaser.Game {
    csocket: WebSocket;
    constructor(wsPath, container) {
        var bootState = new Boot(wsPath);
        this.state.add('Boot', bootState, false);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM