0

as a former Java Engineer I'm struggling to have an interface as callback in Typescript/Javascript.

I'm having a "worker" class where I call doWork(..., myWorkerCallback) The callback consists of different callback methods.

interface WorkerCallback {
    onWorkDone() : void
    onError(message: String) : void
    ...
}

In my calling component I'd have a member that implements that Callback-Interface.

myWorkerCallback: WorkerCallback = {
    onWorkDone() {
    ...
    }
}

now I need to access the state of the React component inside these callback methods. So I need to bind this callback member, right? But how to bind this interface member

1 Answer 1

1

I am not sure about react-native but typical way to bind something to function is to use closures:

interface IWorkerCallback {
    onWorkDone(): void;
    onError(message: string): void;
    // ...
}

// Option 1: using object literals
function makeWorkerCallback(state: SomeState): IWorkerCallback  {
    return {
        onWorkDone: () => {
            state.update();
        },
        onError: () => { }
    }
}

// Option 2: using classes
class WorkerCallback implements IWorkerCallback {
    state: SomeState;

    constructor(state: SomeState) {
        this.state = state;
    }

    onWorkDone() {
        this.state.update();
    }

    onError(message: string) { }
}

// Usage example
const myWorkerCallback1 = makeWorkerCallback(state1);
const myWorkerCallback2 = makeWorkerCallback(state2);

const myWorkerCallback3 = new WorkerCallback(state3);
const myWorkerCallback4 = new WorkerCallback(state3);

Though at this point these objects are not callbacks. They are more. I would rename them "FooBarHandler" or something.

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

4 Comments

ok, so it seems I need to bind every individual function of the interface. there's no binding of an Interface instance.
I probably missing something in your problem. makeWorkerCallback will need to return all functions defined in interface. Not just onWorkDone (I will update my answer). So thus binding automatically happens for all functions.
Updated answer. If it is still not clear then I will need more detailed question with more examples.
thanks, but i need to access/bind the state of the react component, so just passing it in the constructor does not work i guess.

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.