1

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

2
  • 1
    I may be missing what you're looking to accomplish with this function. But generally if you're performing an asynchronous operation and want the user to be able to attach a .done() callback (or .then() I suppose) then you'd return a Promise from that operation: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/… Commented Apr 24, 2020 at 14:47
  • as it's written, any time done() is called, it will just instantly call the function that was passed to it without waiting! if you would like to attach a callback that can be called later, consider using an EventEmitter, otherwise store the callback when done() is called (don't call it instantly) and execute that callback if it exists in loadTiledmap() Commented Apr 24, 2020 at 14:47

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.