We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi,
I'm writing some sketches in p5 using instance mode. Some of them are getting pretty big, so I was wondering if there was any way to move some of the functionality into multiple files. My initial attempt was to move all the mouse event functions into another file, then import it into the main sketch file and call a function to register them:
test.js:
import registerFunctions from './mouseHandler.js';
let sketch = function(p5) {
var a = 5;
p5.setup = function() {
...
registerFunctions(p5);
};
p5.draw = function() {...};
};
let p5Sketch = new p5(sketch , 'canvas-holder');
mouseHandler.js:
function _mousePressed() {
console.log(a); // Obviously wont work
}
export default function registerInputFunctions(p5) {
p5.mousePressed = _mousePressed;
}
My obvious issue is that I can't access the inner variables from test.js, so this method wont be very useful. So is there any way I can split the sketch into multiple files and somehow access the variables in the sketch from each of the other files?
Thanks in advance :)>-
Answers
function
sketch().var
a as a closure.function
of sketch(), the former can't access the latter'svar
a closure. :(var
a as a property of p5 as well, just like setup() & draw() already are; effectively exporting them all: :ar!this
within your imported mousePressed(). *-:)http://Bl.ocks.org/GoSubRoutine/ce702dbf832b11732ddae6b7c7d49f9d
index.html:
mouseHandler.js:
sketch.js:
@GoToLoop Can you comment in the difference between
p.draw = draw.bind(p);
andp.draw = function () { .... }
. Do I need to use bind here in this case?Kf
this
inside afunction
refers to theobject
which had invoked it. ~O)object
itself. B-)this
inside those callbacks, thatthis
is an instance ofclass
p5 of the current sketch. :>object
is calling back draw(), isn't an instance ofclass
p5! 8-}this
to refer to current p5's instanceobject
, represented by closured parameter p. :ar!this
: :-@this
, read this article below: :-Bhttps://Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Thxs @GoToLoop for your comments.
kf