playcanvas / playcanvas/engine

API to make registering events in scriptType easier

Open
#4,910 22 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

area: scripts enhancement
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.