Chaplin.mediator → Source

It is one of the basic goals of Chaplin to enforce module encapsulation and independence and to direct communication through controlled channels. Chaplin’s mediator object is the enabler of this controlled communication. It implements the Publish/Subscribe (pub/sub) pattern to ensure loose coupling of application modules, while still allowing for ease of information exchange. Instead of making direct use of other parts of the application, modules communicate by events, similar to how changes in the DOM are communicated to client-side code. Modules can listen for and react to events, but also publish events of their own to give other modules the chance to react. There are only three basic methods for this application-wide communication: subscribe, unsubscribe and publish.

Note: If you want to give local pub/sub functionality to a class, take a look at the EventBroker.

Methods

subscribe(event, handler, [context])

A wrapper for Backbone.Events.on. See Backbone documentation for more details.

unsubscribe([event], [handler], [context])

A wrapper for Backbone.Events.off. See Backbone documentation for more details.

publish(event, [*args])

A wrapper for Backbone.Events.trigger. See Backbone documentation for more details.

Usage

In any module that needs to communicate with other modules, access to the application-wide pub/sub system can be gained by requiring Chaplin as a dependency. The mediator object is then available as Chaplin.mediator.

define ['chaplin', 'otherdependency'], (Chaplin, OtherDependency) ->
define(['chaplin', 'otherdependency'], function(Chaplin, OtherDependency) {})

For example, if you have a session controller for logging in users, it will tell the mediator that the login occurred:

Chaplin.mediator.publish 'login', user
Chaplin.mediator.publish('login', user);

The mediator will propagate this event to any module that was subscribed to the 'login' event, as in this example:

Chaplin.mediator.subscribe 'login', @doSomething
Chaplin.mediator.subscribe('login', this.doSomething);

Finally, if this module needs to stop listening for the login event, it can simply unsubscribe at any time:

Chaplin.mediator.unsubscribe 'login', @doSomething
Chaplin.mediator.unsubscribe('login', this.doSomething);