0

I have a callback function and would like to pass in parameters. I read you can use Apply but I found it to be overly complex and confusing. Here is my binding function:

function onPlotZoom (event, plot, args ) {
   $.each( plot.getAxes(), function( event, axisName, axis) {
      options[axisName].min = axis.min;
      options[axisName].max = axis.max;
      options[axisName].scale = axis.scale;
   }
}


$( "#plot" ).bind( "plotzoom", onPlotZoom );

My script also has variables which listen on the document whether shift and ctrl pressed and stored like so:

var isShiftPressed = false;
var isCtrlPressed = false;

How can I pass these 2 variables into the callback onPlotZoom? I have tried the following:

$( "#plot" ).bind( "plotzoom", onPlotZoom( isShiftPressed, isCtrlPressed ) );

function onPlotZoom (event, plot, isShiftPressed, isCtrlPressed ) {
   $.each( plot.getAxes(), function( event, axisName, axis) {
      if(isShiftPressed) {
          //do stuff
      }
      if(isCtrlPressed) {
          // do stuff
      }
      options[axisName].min = axis.min;
      options[axisName].max = axis.max;
      options[axisName].scale = axis.scale;
   }
}

another method I tried was using args and obtaining the property. But this resulted in a cannot find property 0 error:

$( "#plot" ).bind( "plotzoom", onPlotZoom( isShiftPressed, isCtrlPressed ) );

function onPlotZoom (event, plot, args) {
     var isShiftPressed = args[0];
     var isCtrlPressed  = args[1];
    // stuff
}
DawnAxolotl
  • 13
  • 1
  • 3
  • Don't pass them, don't declare them as parameters, just use them through closure! – Bergi Sep 23 '21 at 17:14
  • "*I read you can use Apply*" - not really, no. Where did you read that? – Bergi Sep 23 '21 at 17:15
  • I read it somewhere on here but I may have misread. I tried using them without passing as param but when debugging within the function if statements it states isShiftPressed and isCtrlPressed is invalid. – DawnAxolotl Sep 23 '21 at 17:33
  • Could you please explain how to do so? Im not too familiar with JS. – DawnAxolotl Sep 23 '21 at 17:38
  • Start learning about closures :-) You say your script "*has variables*", are they in scope? – Bergi Sep 23 '21 at 17:47
  • Sorry mean to say `undefined` not `invalid` in my previous comment. the variables are declared as var at the top of the script, I assume global space so i think it would be in scope of the function. – DawnAxolotl Sep 23 '21 at 17:48
  • Yes they should then. Are you sure you did not re-declare them somewhere in between (e.g. as function parameters)? – Bergi Sep 23 '21 at 18:23

0 Answers0