I like to write my callback functions in a private namespace and then call them by reference. eg
var myCallback = function() {
};
// ... somewhere else in the class.
SomeOtherObject.doSomething(myCallback);
This makes the code neater and more extendable. However when I need to pass any parameters to the callback from the original function it becomes messy and I have to enclose the callback reference in a closure. eg
var myCallback = function(a_var, another_var) {
};
// ... somewhere else in the class.
a_var = "something";
SomeOtherObject.doSomething(function(another_var) {
myCallback(a_var, another_var);
};
This results in the callback requiring two function calls instead of one, creating overhead. It also means I have an undocumented anonymous function for the closure – or I document both functions. (It’s not so much the missing function definition which is annoying as the parameter definitions.) If the callback is small – as good functions are – then it makes it seem not worthwhile to put it the private scope.
What is the best way to do this?
Partial application implementations allow you to pass variables in this way.
For example, using native ES5’s
bind:another_varwill be passed to that function when calledIt’s not supported everywhere though, so you can grab the one from underscore and use that instead.