Mediator


The mediator module is for managing communication between separete bits of code. This helps to keep your code a little cleaner and a little more decoupled.

The mediator uses the pub/sub pattern. Check out the link for a great explanation by Addy Osmani. If you've never used or heard of this pattern, the gist is that you publish to a "topic" and anyone can subscribe to that topic. A simple analog would be a radio station. The radio station will broadcast, or "publish", and the listeners who are tuned in, or "subscribed", will hear the broadcast and be able to do something with that information.

Imagine you're building a project with pjax and you have a fly out navigation. If you click a link in the navigation, pjax will fire and replace the content. This content will normally not include the global navigation, so the content is replaced behind the navigation making it appear like nothing has happened. You can hook into the Router's afterEach method and leverage the mediator to enable communication between those disperate pieces of code.

It might look something like this:

// app.js

import $mediator from 'wee-mediator';

$router.pjax().map([
    {
        path: '/',
        handler: [
            () => load('naivgation'),
            () => load('home'),
        ]
    },
    {
        path: '/about',
        handler: [
            () => load('naivgation'),
            () => load('about'),
        ]
    }
]).afterEach(() => {
    $mediator.emit('navigated');
}).run();
// navigation.js

import $mediator from 'wee-mediator';

class Navigation {
    constructor() {
        $mediator.on('navigated', () => {
            this.close();
        });
    }

    close() {
        //
    }
}

The use cases really are nearly endless.

You can pass a payload to the emit method and use that in the logic for your subscriber functions. Let's say you have a class that shows alerts to the user and want to be able to use that throughout your application:

// alerts.js

import $mediator from 'wee-mediator';

$mediator.on('alert', (data) => {
    new Alert(data);
});

class Alert {
    constructor({ type, message, onClick }) {
        this.type = type;
        this.message = message;
        this.onClick = onClick;
    }

    // ...
}
import $events from 'wee-events';
import $mediator from 'wee-mediator';

$events.on(':element', 'click', () => {
    $mediator.emit('alert', {
        type: 'error',
        message: 'There was a problem',
        onClick: () => {
            // do stuff
        }
    });
});

Read more detailed documentation about the mediator here