JS Module Communication (Mediator)

The Mediator is a tool for TinyCore developed by Mawrkus an is available on github.

The mediator tool implements a simple publish/subscribe system, for inter-modules communication and all this in less than 1Kb minified.

Why do I need a publish/subscribe system?

Sometimes you need modules to communicate between them, but if you call directly from one to another you are adding critical dependencies.It's very common that one day someone or even you, needs to modify one of this modules, or delete some functions adding a bug to the another one. Use the mediator to subscribe and publish events that will other modules can hear and trigger some events with a total independence of each module.

API

var FrontendMediator = {
    subscribe : function ( topics, handler, context ) {},
    publish : function ( topic, data ) {},
    unsubscribe : function ( topics ) {},
    unsubscribeAll : function () {}
};

Example

The Mediator can be requested explicitly via FrontendMediator :

FrontendMediator.publish( 'phone:call', { from : '+34123456789' } );

Here you have an example on module implementation:

FrontendCore.define( 'phone', ['devicePackage'], function ( mediator )
{
    return {
        onStart : function ()
        {
            var self = this;

            FrontendMediator.publish( 'phone:boot', { when : +new Date() } );

            FrontendMediator.subscribe( 'phone:call', function ( oTopic )
            {
                var oCallData = oTopic.data;
                self.displayMessage( 'Call from '+oCallData.from );
            } );

            // Subscribe to several topics and...
            // ...specify the context in which "onBatteryStateChanged" should be executed.
            FrontendMediator.subscribe( ['battery:charged', 'battery:empty'], this.onBatteryStateChanged, this );
        },
        onStop : function ()
        {
            var self = this;

            FrontendMediator.unsubscribe( ['phone:call', 'battery:charged'] );
            FrontendMediator.unsubscribe( 'battery:empty' );
            // FrontendMediator.unsubscribeAll();
        },
        onBatteryStateChanged : function ( oTopic )
        {
            var sTopicName = oTopic.name,
                sMsg = sTopicName === 'battery:charged' ?
                                        'Battery fully charged.' :
                                        'Battery is empty!';

            this.displayMessage( sMsg );
        },
        displayMessage : function ( sMsg )
        {
            alert( sMsg );
        }
    };
} );