Skip to content
Jasper edited this page Sep 6, 2013 · 3 revisions

PhysicsJS uses the concept of Publishing and Subscribing to events to encourage loose coupling and modularity.

Callback subscribed to an event will receive a data object with all information about the event, including:

  • topic - the event name
  • handler - the callback function reference
  • scope - the scope of the event (usually the world)
  • any other data specific to the event

These events are generally mediated through the world object. The world itself emits the following events:

  • add:body (data.body contains the body added)
  • add:behavior (data.behavior contains the behavior added)
  • add:integrator (data.integrator contains the integrator added)
  • add:renderer (data.renderer contains the renderer added)
  • remove:body (data.body contains the body removed)
  • remove:behavior (data.behavior contains the behavior removed)
  • render (data.bodies is the array of bodies in the world, data.renderer is the renderer)
  • step

NB: Behaviors may publish and subscribe to other events.

To subscribe to an event:

world.subscribe(EVENT_NAME, function( data ){
    // ...
}, thisRef, PRIORITY);

The EVENT_NAME is a string. thisRef is an optional scope to bind the callback to. PRIORITY is similar to unix priorities. A callback subscribed with a higher priority will be executed sooner than one with a lower priority.

To unsubscribe:

world.unsubscribe( EVENT_NAME, callbackFn );

To publish an event:

world.publish({
    topic: EVENT_NAME,
    // ...
});

Clone this wiki locally