Sign in to follow this  
Tymski

.off() doesn't remove .on() event listeners

Recommended Posts

I'm debugging memory leaks in my pixi application. And i stumbled on this beauty:

sprite = new PIXI.Sprite();
sprite.on('pointerdown',function(){});
sprite.off();

And:

sprite._events
>> Object { pointerdown: Object }

sprite._events has pointerdown event listener even after I deleted it with off(). Why???

 

 

Share this post


Link to post
Share on other sites

.off has the same signature as .on does. So you have to pass the event id and a reference to the same function instance that you passed to the .on function. In your example code that would not even be possible because you have used an anonymous function which you defined within the call to .on itself. If you want to remove the event listener later then you definitely don't want to use that approach! You need to define the listener function elsewhere and have a way of referencing it either by name or through assigning it to a variable. Then pass that reference to both the .on and the .off calls. 

Pixi uses EventEmitter3 for event handling so you can easily check the source code to confirm that this is the way it works:

https://github.com/primus/eventemitter3/blob/master/index.js#L236

So your example code needs to be like this:

const sprite = new PIXI.Sprite();
const eventHandler = function(){};
sprite.on('pointerdown', eventHandler);
sprite.off('pointerdown', eventHandler);

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.