Add a variable to a javascript callback -


i using library must define callback function, , library execute function upon event:

// initialize callback library. // `lib` main variable library , defined globally function initializations() {     var extra_var = 'pass me callback';     var libprops = {         libcallback: function(settings) { stuff }     };     lib.reconfigure(libprops); } 

the library runs callback (i have no control on this):

var settings = 'xyz'; libprops.libcallback(settings); 

so clearly, 1 of variables input defined callback settings variable. want pass in variable of own:

function mycallback(settings, extra_var) {     // stuff involving settings     // stuff involving extra_var } 

how can define libprops.libcallback within initializations() extra_var passed in, function mycallback defined elsewhere? ie so:

function mycallback(settings, extra_var) {     // stuff involving settings     // stuff involving extra_var } 

is possible? reason want define mycallback() outside of initializations() mycallback() quite large , messy have defined inside initializations().

it seems closure solve issue, i'm not quite sure how construct it. here preliminary attempt:

function initializations() {     var extra_var = 'pass me callback';     var libprops = {         libcallback: (function(settings) {             mycallback(settings, extra_var)         })(extra_var)     };     lib.reconfigure(libprops); } 

you have closure, therefore don't need pass in extra_var anywhere, it's available anonymous callback function already, extra_var

function initializations() {     var extra_var = 'pass me callback';     var libprops = {         libcallback: function(settings) {             // stuff              // can stuff extra_var here         }     };     lib.reconfigure(libprops); } 

as per information in comment, call myfunction in anonymous callback, passing in extra_vars second parameter (or first if want, doesn't matter, it's function)

function initializations() {     var extra_var = 'pass me callback';     var libprops = {         libcallback: function(settings) {             mycallback(settings, extra_var);         }     };     lib.reconfigure(libprops); } 

there's way using .bind - however, no need such gymnastics in such simple scenario


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -