saqirmdev
saqirmdev

Reputation: 85

Typescript -> Calling function which will call callback in another function

I'm asking maybe something too weird but i'm not sure

I'm trying to make .done() function in Typescript using OOP

My code looks like:

    // Calling this callback out of Class map/terrain
    terrain.done(() =>
    {
        // Do something when terrain is Done
    });

Another code is loading terrain, now i have function whit i want to run this callback.

   private loadTiledmap():void
   {
     .... //loadTiledmap is called when all resources are loaded
       this.done; // Trigger the callback
   }

   public done(callback: () => void ): void
   {
       callback();
   }

The both this.done and terrain.done(() will call the callback, but i have no idea how to trigger terrain.done(() somewhere else in code. Thanks for all your helps and tips

Upvotes: 1

Views: 824

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187014

It sounds like you want done(callback) to register the callback, and then you want to loadTiledmap to call that callback when it's completed it's work?

In that case, you just need to save the function on your class instance, and then run that callback.

class MyClass {
    private doneCallback: (() => void) | undefined

    // Save the callback function
    public done(callback: () => void ): void
    {
        this.doneCallback = callback;
    }

    private loadTiledmap():void
    {
       // ... loadTiledmap is called when all resources are loaded
       this.doneCallback?.(); // Trigger the callback
    }
}

Playground

Upvotes: 2

Related Questions