I have a class that has a callback function that gets triggered on some event. The user of the class instance is expected to do stuff on the instance itself, inside this callback function. So I am wondering if I should add the instance itself as an argument to the callback.
type CallbackType = (foo: Foo, n: number) => void; // <-- 1
// type CallbackType = (n: number) => void; <-- 2
class Foo {
private n: number; // something that keeps changing
private callback: CallbackType;
addCallback(callback: CallbackType) { this.callback = callback; }
eventloop() {
/* do some stuff that changes `n` */
if (someTrigger) this.callback(this, this.n); // <-- 1
// if (someTrigger) this.callback(this.n); <-- 2
}
}
class Bar {
private foo: Foo;
constructor() {
this.foo = new Foo();
this.foo.addCallback((foo, n) => { // <-- 1
this.something(n);
foo.someFunc();
});
// this.foo.addCallback((n) => { <-- 2
// this.something(n);
// this.foo.someFunc();
// });
}
}
In #1, with the foo
argument, you expect stuff to happen with foo inside the callback (like in the visitor pattern). #2 looks shorter and simpler, but feels sneaky since you do something with the instance itself, within the callback, (kind of) without Foo
knowing it. How should I do this?