Docs

Everything You Need to Know

Mediators

Intro

Mediators allow you to create loosely coupled code. They serve as the glue to bind the different parts of your app together. Mediators sit between the different parts of your app and handle complex tasks so that your models and views don't have to. You could use a mediator to process data before post it to a remote server, or before persisting it in a local dataStore.

As useful as mediators are, they are optional. You can build a very efficient app without writing a single mediator. However, if you are using any type of navigation, including routing, mediators are running behind the scenes.

ChocolateChip-UI uses an evented bus system to enable mediators. The events that mediators respond to are called "topics". You can use delimiters to create namespaced topics for your mediators. When you dispatch a topic, any mediator listening to it will fire. And like normal events, you can have multiple mediators listening to the same topic.

You can pass data to a mediator when you run it. And you can define mediator's callback to automatically capture that data. To define a mediator, you use $.on(). The first argument is the topic, followed by the callback to execute. Notice that the following callback is set to capture any data that gets passed:

// Access passed data in the callback using `data`:
var fooMtor = $.on('Foo', function(data) {
  console.log('What we got: ' + data);
});
// Execute the mediator with a message:
fooMtor.run('Something for you here.');
// Result: "What we got: Something for you here."

You can also define a mediator that is executed like any other function. For example:

var FooMtor = $.on('foo', function() {
  console.log('This is fooMtor running!');
});
// Execute the mediator:
fooMtor.run();