Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy would one use the Publish/Subscribe pattern (in JS/jQuery)?
    primarykey
    data
    text
    <p>So, a colleague introduced me to the publish/subscribe pattern (in JS/jQuery), but I'm having a hard time getting to grips with <em>why</em> one would use this pattern over 'normal' JavaScript/jQuery.</p> <p>For example, previously I had the following code...</p> <pre><code>$container.on('click', '.remove_order', function(event) { event.preventDefault(); var orders = $(this).parents('form:first').find('div.order'); if (orders.length &gt; 2) { orders.last().remove(); } }); </code></pre> <p>And I could see the merit of doing this instead, for example...</p> <pre><code>removeOrder = function(orders) { if (orders.length &gt; 2) { orders.last().remove(); } } $container.on('click', '.remove_order', function(event) { event.preventDefault(); removeOrder($(this).parents('form:first').find('div.order')); }); </code></pre> <p>Because it introduces the ability to re-use the <code>removeOrder</code> functionality for different events etc.</p> <p>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 <a href="https://gist.github.com/661855" rel="noreferrer">jQuery tiny pub/sub</a>)</p> <pre><code>removeOrder = function(e, orders) { if (orders.length &gt; 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')); }); </code></pre> <p>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 <em>how</em> to implement this pattern only cover just as basic examples as my own.</p> <p>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!</p> <p>Could you explain <strong>succinctly</strong> why and in what situations this pattern is advantageous? Is it worth using the pub/sub pattern for code snippets like my examples above?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload