You would use this when you have several parts that work together in unlimited combinations, where you do not know all the combinations ahead of time or where it is more efficient to take all the combinations.
Say you built a social media application and you wrote a class to encapsulate a list of users. On some screens, clicking on a user in the list opens their profile, on another screen, perhaps clicking on the user searches for each comment they left, and something else happens on the third screen.
If you want to write this not using the / pubsub mediator, you will end up with a bunch of if statements in the onclick event ...
UserList.prototype.onUserClick = function(user) { // Check if we're supposed to open a popup if (this.mode === 'profile') // Check for something else else if (this.mode === 'something else') // Check for another case else if (this.mode === 'foo') }
A mediator is a solution to this problem because it does not require the UserList to know every single situation that it may be in. Instead, the above code in UserList could simply be refined for translation when clicking on a user ...
UserList.prototype.onUserClick = function(user) { this.publish('user-click', user); }
Then each of your other screens or fragments of the user interface can simply listen to the message for the user ...
// On pages where there needs to be a popup profile Mediator.onMessage('user-click', function(data) { showProfilePopup(data); }); // Or perhaps on a search page SearchBox.onMessage('user-click', function(data) { this.searchByUser(data); });
In addition, when the pick begins to shine, this is because these other components of the user interface, such as SearchBox
, are not specifically interested when the UserList
launches a user click, they are only interested in when a click is published, another UI elements on the page also can trigger a user click, and these parts can respond to it.
On the side, the note className = { }
does not create a class. You probably need className = function() { }
.