Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.from the book Design Patterns. Elements of Reusable Object-Oriented Software.
That means you have your modules, wich will publish and subscribe to events without knowing anything about each other. This way you can also have subscribers to events which will never be published and publishers which will not be subscribed to. It will not break your application if that happens.
Because it is good to not reinvent the wheel everytime you code something, download/clone mediator.js from Github. It is a free MIT licensed library with the Design Pattern already implemented.
Let me show you an example usage with a simple module that calculates the square of a rectangle. Let us start with the following HTML:
Before we can use Mediator.js, we have to instantiate it:
Now we make a math geometry rectangle module which calculates two numbers to a square:
Let the user enter the length and height of the rectangle and make an output:
That is it. So we have now 3 little modules and some kind of controller, which puts everything together. If we forgot to include for example the output.js we would simply get no output, but also no error. This is a good thing if you have a really large application and misspelled for example an event, because only that one little part will break and not the complete functionality. Of course you have to check now a little bit more if you really included every needed file for your app, but if you use something like Grunt to make a minified version of your files and bind them all together, then it should be no problem.