playcanvas / playcanvas/engine
API to make registering events in scriptType easier
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 16.8k
- Forks
- 2k
- Avg merge
- 4h 32m
- Merged PRs (30d)
- 222
Description
A common issue with developers new to PlayCanvas is ensuring that event listeners to objects like the mouse are cleaned up properly when the scriptType is destroyed (eg destroying the Entity or changing scenes)
Users either don't know and/or assume it's done automatically. And to do it correctly requires some boilerplate. eg:
// initialize code called once per entity
BoxPlacement.prototype.initialize = function () {
if (this.app.touch) {
this.app.touch.on('touchstart', this.onTouchStart, this);
}
this.app.mouse.on('mousedown', this.onMouseDown, this);
this.on('destroy', function () {
if (this.app.touch) {
this.app.touch.off('touchstart', this.onTouchStart, this);
}
this.app.mouse.off('mousedown', this.onMouseDown, this);
}, this);
};
Could we introduce some API to make this easier/automatic? Such as a function that automatically removes the listener when the scriptType is destroyed? It would turn the above code into:
BoxPlacement.prototype.initialize = function () {
if (this.app.touch) {
this.listen(this.app.touch, 'touchstart', this.onTouchStart, this);
}
this.listen(this.app.mouse, 'mousedown', this.onMouseDown, this);
};
And would also work with anonymous functions too
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by tracing scriptType destruction and the existing event listener APIs used in the issue's examples. Define an API that removes listeners when the scriptType is destroyed, including listeners registered with anonymous functions; done means the proposed shorter usage works without manual cleanup.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- game-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100