I am using a library where I must define a callback function, and the library will execute this function upon a certain event:
// initialize the callback for the library.
// `lib` is the main variable for the library and is defined globally
function initializations() {
var extra_var = 'pass me into the callback';
var libprops = {
libcallback: function(settings) { do stuff }
};
lib.reconfigure(libprops);
}
The library then runs the callback like so (I have no control over this):
var settings = 'xyz';
libprops.libcallback(settings);
So clearly, one of the variables input to my defined callback will be the settings variable. However I also want to pass in a variable of my own:
function mycallback(settings, extra_var) {
// do stuff involving settings
// do stuff involving extra_var
}
How can I define libprops.libcallback within initializations() so that extra_var is passed in, but with function mycallback defined elsewhere? Ie like so:
function mycallback(settings, extra_var) {
// do stuff involving settings
// do stuff involving extra_var
}
Is this possible? The reason I want to define mycallback() outside of initializations() is that mycallback() is quite large and its messy to have it defined inside initializations().
It seems like a closure would solve the issue, but I'm not quite sure how to construct it. Here is a preliminary attempt:
function initializations() {
var extra_var = 'pass me into the callback';
var libprops = {
libcallback: (function(settings) {
mycallback(settings, extra_var)
})(extra_var)
};
lib.reconfigure(libprops);
}
extra_varanywhere, it's available to your anonymous callback function already, asextra_varmycallback()outside ofinitializations(). I have updated the question to include this important requirement. Sorry to change the game. It was obvious to me, but I realized it was not originally included in the question :Plibcallback: function(settings) {..}, remove the function call withextra_var