Skip to content
Merged
17 changes: 17 additions & 0 deletions src/core/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,19 @@ class p5 {
this._events.devicemotion = null;
}

// Function to call registered before and after hooks for preload and setup
function callRegisteredHooksFor(hookName) {
const target = this || p5.prototype;
if (target._registeredMethods.hasOwnProperty(hookName)) {
const methods = target._registeredMethods[hookName];
for (const method of methods) {
if (typeof method === 'function') {
method.call(this);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work on this helper function! Just for consistency, now that we have this helper, can we update the pre/post draw hooks to use this too? Currently that happens here:

context._registeredMethods.pre.forEach(callMethod);

I also notice that for pre/post draw, rather than passing this to call, they pass context, where it is defined as:

const context = this._isGlobal ? window : this;

Maybe we can do that here too?

}
}
}
}

this._start = () => {
// Find node if id given
if (this._userNode) {
Expand All @@ -241,6 +254,7 @@ class p5 {

const context = this._isGlobal ? window : this;
if (context.preload) {
callRegisteredHooksFor('beforePreload');
// Setup loading screen
// Set loading screen into dom if not present
// Otherwise displays and removes user provided loading screen
Expand Down Expand Up @@ -286,6 +300,7 @@ class p5 {
if (loadingScreen) {
loadingScreen.parentNode.removeChild(loadingScreen);
}
callRegisteredHooksFor('afterPreload');
if (!this._setupDone) {
this._lastTargetFrameTime = window.performance.now();
this._lastRealFrameTime = window.performance.now();
Expand Down Expand Up @@ -322,6 +337,7 @@ class p5 {
};

this._setup = () => {
callRegisteredHooksFor('beforeSetup');
// Always create a default canvas.
// Later on if the user calls createCanvas, this default one
// will be replaced
Expand Down Expand Up @@ -369,6 +385,7 @@ class p5 {
if (this._accessibleOutputs.grid || this._accessibleOutputs.text) {
this._updateAccsOutput();
}
callRegisteredHooksFor('afterSetup');
};

this._draw = () => {
Expand Down