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?