Button box callback function cannot assign value to existing global variable

I’m using version v2024.2.5

I have a button box with callback code:

myvar=True

where myvar is previously defined on a ‘begin_experiment’ tab of a code component in an earlier routine.
This works fine running in local psychopy/python however when I run it online the JS code does not try to assign the value to the existing ‘global’? variable - instead it creates a local instance
if (!oldbb.wasClicked) {
// end routine when oldbb is clicked
continueRoutine = false;
var myvar;
newold_decision = false;
}

and so it’s then not available after the close bracket.
Is this a bug? I can’t find any examples of how to use the callback section for button boxes - do I have to create a function and pass that a value to then assign to the pre-existing ‘global’ variable. Thi sfeels overkill.

thanks,

John

Hi John,

Builder mainly translates standard patterns, so custom code often needs separate Python and JavaScript versions. Online JS isn’t exactly wrong; it creates a block-local ‘var myvar’, so the fix is to assign to a real global instead.

JS

window.myvar = false; // declare global once
if (!oldbb.wasClicked) {
  continueRoutine = false;
  window.myvar = true; // update the global
}
psychoJS.experiment.addData('myvar', window.myvar);

Python

myvar = False
if not oldbb.wasClicked:
    continueRoutine = False
    myvar = True
thisExp.addData('myvar', myvar)

Hope this helps.

In recent versions of PsychoPy the callback code works without issues. With versions with this bug I removed the callback function and checked clicks in End Routine.

1 Like