Level up javascript function to root of scope

Hello, I’m trying to get p5.js library working on Sage 8.5.3.

p5.js has an onload callback inside, to call setup() function in the top level of the scope. Means that, when I write my function inside 'common' of assets/scripts/main.js, it is not available on the top level:

'common': {
      init: function() {
        function setup() {
          createCanvas(500, 500);
          background(200);
        }
      },

So, my question is: is it possible to write JS available in the top level using assets/scripts/main.js file?

There is a workaround, using instantiation mode that works:

var sketch = function(p) {
    p.setup = function () {
      p.createCanvas(500, 500);
      p.background(200);
    };
  };
  new p5(sketch);

but I would like to ask if is it possible using global mode with Sage 8. Thank you!

Sure. Just put your code before this line.

But I’d use the second option if you want to scoped code for routes, etc.

1 Like

Ok! Thank you.

(20 chars)

1 Like

Or you could do:

window.setup = function() {
          createCanvas(500, 500);
          background(200);
}

Just make sure the callback is loaded first :wink:

(however, I’d not recommend to use the global scope)

1 Like