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'));
});
我确实读过关于这个模式的书,但我无法想象为什么有必要这样做.我看到的教程解释了如何实现这个模式,这些教程只包含了和我自己一样的基本示例.
我想pub/sub的用处会在更复杂的应用程序中显现出来,但我无法想象这样的应用程序.恐怕我完全没有抓住要点,但如果有的话,我想知道要点是什么!
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?