Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add unregisterMethod function #6426

Merged
merged 3 commits into from
Sep 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions contributor_docs/creating_libraries.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,20 @@ p5.prototype.getData = function (callback) {
return ret;
};
```
### Use **registerMethod()** to register functions with _**p5**_ that should be called at various times.

### Use **registerMethod()** and **unregisterMethod()** to register and unregister functions with _**p5**_ that should be called at various times.

```js
p5.prototype.doRemoveStuff = function () {
// library cleanup stuff
};
p5.prototype.registerMethod('remove', p5.prototype.doRemoveStuff);

// Unregister the method when it's no longer needed.
p5.prototype.unregisterMethod('remove', p5.prototype.doRemoveStuff);
```
Method names you can register include the following list. Note that you may need to define the function before you register it.

Method names you can register and unregister include the following list. Note that you may need to define the function before you register it.

* **pre** — Called at the beginning of `draw()`. It can affect drawing.
* **post** — Called at the end of `draw()`.
Expand Down
18 changes: 18 additions & 0 deletions src/core/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,24 @@ class p5 {
target._registeredMethods[name].push(m);
}

unregisterMethod(name, m) {
const target = this || p5.prototype;
if (target._registeredMethods.hasOwnProperty(name)) {
const methods = target._registeredMethods[name];
const indexesToRemove = [];
// Find all indexes of the method `m` in the array of registered methods
for (let i = 0; i < methods.length; i++) {
if (methods[i] === m) {
indexesToRemove.push(i);
}
}
// Remove all instances of the method `m` from the array
for (let i = indexesToRemove.length - 1; i >= 0; i--) {
methods.splice(indexesToRemove[i], 1);
}
}
}

// create a function which provides a standardized process for binding
// globals; this is implemented as a factory primarily so that there's a
// way to redefine what "global" means for the binding function so it
Expand Down