So, a colleague introduced me to the publish/subscribe pattern (in JS/jQuery), but I'm having a hard time getting to grips with why one would use this pattern over 'normal' JavaScript/jQuery.
For example, previously I had the following code...
$container.on('click', '.remove_order', function(event) {
event.preventDefault();
var orders = $(this).parents('form:first').find('div.order');
if (orders.length > 2) {
orders.last().remove();
}
});
And I could see the merit of doing this instead, for example...
removeOrder = function(orders) {
if (orders.length > 2) {
orders.last().remove();
}
}
$container.on('click', '.remove_order', function(event) {
event.preventDefault();
removeOrder($(this).parents('form:first').find('div.order'));
});
Because it introduces the ability to re-use the removeOrder
functionality for different events etc.
But why would you decide to implement the publish/subscribe pattern and go to the following lengths, if it does the same thing? (FYI, I used jQuery tiny pub/sub)
removeOrder = function(e, orders) {
if (orders.length > 2) {
orders.last().remove();
}
}
$.subscribe('iquery/action/remove-order', removeOrder);
$container.on('click', '.remove_order', function(event) {
event.preventDefault();
$.publish('iquery/action/remove-order', $(this).parents('form:first').find('div.order'));
});
I've read about the pattern for sure, but I just can't imagine why this would ever be necessary. The tutorials I've seen that explain how to implement this pattern only cover just as basic examples as my own.
I imagine that the pub/sub's usefulness would make itself apparent in a more complex application, but I can't imagine one. I'm afraid that I am completely missing the point; but I'd like to know the point if there is one!
Could you explain succinctly why and in what situations this pattern is advantageous? Is it worth using the pub/sub pattern for code snippets like my examples above?
Simple answer The original question was looking for a simple answer. Here's my attempt.
Javascript doesn't provide any mechanism for code objects to create their own events. So you need a kind of event mechanism. the Publish / subscribe pattern will answer this need, and it's up to you to choose a mechanism that best suits your own needs.
Now we can see a need for the pub/sub pattern, then would you rather have to handle DOM events differently from how you handle your pub/sub events? For the sake of reducing complexity, and other concepts such as separation of concerns (SoC) you might see the benefit of everything being uniform.
So paradoxically, more code creates a better separation of concerns, which scales well up to very complex web pages.
I hope someone finds this a good enough discussion without going into detail.