Remove Event Listeners with Matter.Events.off in Matter.js

This guide explains how to properly remove event listeners in Matter.js using the Matter.Events.off method. Managing event listeners is essential for preventing memory leaks, avoiding duplicate callback executions, and controlling dynamic physics interactions in your simulations. You will learn the syntax, how to unbind specific callbacks using function references, and how to clear all listeners from an event or target object entirely.

Syntax and Parameters

The Matter.Events.off method unregisters events previously bound with Matter.Events.on. It accepts three parameters:

Matter.Events.off(object, eventNames, callback);

Depending on which arguments you supply, Matter.Events.off can target a single callback, an entire event category, or all events on an object.


1. Removing a Specific Callback

To remove a single listener without affecting other listeners on the same event, you must supply the original function reference. Anonymous functions cannot be removed individually because they do not maintain a reference.

// Define a named callback function
function onCollision(event) {
    const pairs = event.pairs;
    console.log('Collision detected between:', pairs);
}

// Attach the listener
Matter.Events.on(engine, 'collisionStart', onCollision);

// Remove only the onCollision listener
Matter.Events.off(engine, 'collisionStart', onCollision);

2. Removing All Callbacks for a Specific Event

If you omit the callback argument, Matter.js removes all listeners registered under the specified event name for that object.

// Register multiple callbacks to the same event
Matter.Events.on(engine, 'beforeUpdate', updatePositions);
Matter.Events.on(engine, 'beforeUpdate', trackAnalytics);

// Unregister every callback listening to 'beforeUpdate'
Matter.Events.off(engine, 'beforeUpdate');

3. Removing All Events from an Object

To detach every event listener associated with an object, pass only the target object to Matter.Events.off. This is useful when destroying an engine or resetting a scene.

// Removes all events ('collisionStart', 'beforeUpdate', 'afterUpdate', etc.) from the engine
Matter.Events.off(engine);

Common Pitfall: Inline / Anonymous Functions

A frequent mistake is attempting to remove an anonymous function:

// Adding with an anonymous function:
Matter.Events.on(engine, 'collisionStart', function(event) {
    console.log('Collided');
});

// THIS WILL NOT WORK:
Matter.Events.off(engine, 'collisionStart', function(event) {
    console.log('Collided');
});

Because the second function creates a new reference in memory, Matter.js cannot match it to the original listener. Always store your callback in a named variable or function declaration if you plan to unbind it later.