Skip to content

Commit

Permalink
Merge pull request #6426 from capGoblin/add-unregisterMethod
Browse files Browse the repository at this point in the history
add unregisterMethod function
  • Loading branch information
davepagurek authored Sep 22, 2023
2 parents 0c899e9 + e55cd66 commit b806a42
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
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

0 comments on commit b806a42

Please sign in to comment.