Reputation:
I'm in the process of revamping the way I use backbone/require, I found out the hard way on how bad of a practice it is to have modules coupled (I didn't understand decoupling at the time).
I started to play with MinPubSub and understand that for the most part but, from what I read, other modules shouldn't subscribe to other modules (that makes it coupled?). Instead their should be a mediator between all the modules which tell them how to interact.
I assume this mediator is subscribed to all modules and all modules are subscribed to the mediator?
I have no idea how to implement this and yet to find a solid code example on how to implement this with backbone, any help with adding pubsub to backbone would be appreciated.
Sorry of this is to general of a question, trying to wrap my head around the concept and find an decent example of it used extensively.
Upvotes: 0
Views: 1811
Reputation: 8044
Funnily enough, one library I've had a lot of joy with is called Mediator.
It has great examples on the site, but crudely:
$.getJSON('url/to/json', function(json) {
mediator.publish('myData:loaded', {response: json});
});
// Somewhere else
mediator.subscribe('myData:loaded', function(json) {
// Do something
});
Upvotes: 2
Reputation: 19662
Ahem. The pubsub approach is an implementation of the mediator pattern. Your mediator is your pubsub handler.
Let me clarify this. In your pubsub model, you register a channel and publish to it. Anything in there that is potentially listening will get whatever you publish in the order they subscribed.
Contrast this with the formal definition of the mediator pattern:
With the mediator pattern, communication between objects is encapsulated with a mediator object. Objects no longer communicate directly with each other, but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby lowering the coupling.
(Plucked straight from your favourite encyclopedia)
What does this mean for you? That as long as you do not do what someone I know used to do, you're fine. This is absolutely what you want to avoid:
This is where event pub/sub models break down, as it is decoupled in theory, but in practice, you need to know the exact name of the module. Make your events generic enough that you can swap out modules in-place without losing func, and prevent/refrain from getting to other modules directly, and you'll be fine on coupling.
If any of this was not clear, let me know and I'll attempt to clarify.
Upvotes: 2