forked from wellcaffeinated/PhysicsJS
-
Notifications
You must be signed in to change notification settings - Fork 0
PubSub
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.bodycontains the body added) -
add:behavior(data.behaviorcontains the behavior added) -
add:integrator(data.integratorcontains the integrator added) -
add:renderer(data.renderercontains the renderer added) -
remove:body(data.bodycontains the body removed) -
remove:behavior(data.behaviorcontains the behavior removed) -
render(data.bodiesis the array of bodies in the world,data.rendereris 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,
// ...
});