Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8869653
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T17:31:51+00:00 2026-06-14T17:31:51+00:00

So, a colleague introduced me to the publish/subscribe pattern (in JS/jQuery), but I’m having

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T17:31:53+00:00Added an answer on June 14, 2026 at 5:31 pm

    It’s all about loose coupling and single responsibility, which goes hand to hand with MV* (MVC/MVP/MVVM) patterns in JavaScript which are very modern in the last few years.

    Loose coupling is an Object-oriented principle in which each component of the system knows its responsibility and doesn’t care about the other components (or at least tries to not care about them as much as possible). Loose coupling is a good thing because you can easily reuse the different modules. You’re not coupled with the interfaces of other modules. Using publish/subscribe you’re only coupled with the publish/subscribe interface which is not a big deal – just two methods. So if you decide to reuse a module in a different project you can just copy and paste it and it’ll probably work or at least you won’t need much effort to make it work.

    When talking about loose coupling we should mention the separation of concerns. If you’re building an application using an MV* architectural pattern you always have a Model(s) and a View(s). The Model is the business part of the application. You can reuse it in different applications, so it’s not a good idea to couple it with the View of a single application, where you want to show it, because usually in the different applications you have different views. So it’s a good idea to use publish/subscribe for the Model-View communication. When your Model changes it publishes an event, the View catches it and updates itself. You don’t have any overhead from the publish/subscribe, it helps you for the decoupling. In the same manner you can keep your application logic in the Controller for example (MVVM, MVP it’s not exactly a Controller) and keep the View as simple as possible. When your View changes (or the user clicks on something, for example) it just publishes a new event, the Controller catches it and decides what to do. If you are familiar with the MVC pattern or with MVVM in Microsoft technologies (WPF/Silverlight) you can think of the publish/subscribe like the Observer pattern. This approach is used in frameworks like Backbone.js, Knockout.js (MVVM).

    Here is an example:

    //Model
    function Book(name, isbn) {
        this.name = name;
        this.isbn = isbn;
    }
    
    function BookCollection(books) {
        this.books = books;
    }
    
    BookCollection.prototype.addBook = function (book) {
        this.books.push(book);
        $.publish('book-added', book);
        return book;
    }
    
    BookCollection.prototype.removeBook = function (book) {
       var removed;
       if (typeof book === 'number') {
           removed = this.books.splice(book, 1);
       }
       for (var i = 0; i < this.books.length; i += 1) {
          if (this.books[i] === book) {
              removed = this.books.splice(i, 1);
          }
       }
       $.publish('book-removed', removed);
       return removed;
    }
    
    //View
    var BookListView = (function () {
    
       function removeBook(book) {
          $('#' + book.isbn).remove();
       }
    
       function addBook(book) {
          $('#bookList').append('<div id="' + book.isbn + '">' + book.name + '</div>');
       }
    
       return {
          init: function () {
             $.subscribe('book-removed', removeBook);
             $.subscribe('book-aded', addBook);
          }
       }
    }());
    

    Another example. If you don’t like the MV* approach you can use something a little different (there’s an intersection between the one I’ll describe next and the last mentioned). Just structure your application in different modules. For example look at Twitter.

    Twitter Modules

    If you look at the interface you simply have different boxes. You can think of each box as a different module. For example you can post a tweet. This action requires the update of a few modules. Firstly it has to update your profile data (upper left box) but it also has to update your timeline. Of course, you can keep references to both modules and update them separately using their public interface but it’s easier (and better) to just publish an event. This will make the modification of your application easier because of looser coupling. If you develop new module which depends on new tweets you can just subscribe to the “publish-tweet” event and handle it. This approach is very useful and can make your application very decoupled. You can reuse your modules very easily.

    Here is a basic example of the last approach (this is not original twitter code it’s just a sample by me):

    var Twitter.Timeline = (function () {
       var tweets = [];
       function publishTweet(tweet) {
          tweets.push(tweet);
          //publishing the tweet
       };
       return {
          init: function () {
             $.subscribe('tweet-posted', function (data) {
                 publishTweet(data);
             });
          }
       };
    }());
    
    
    var Twitter.TweetPoster = (function () {
       return {
           init: function () {
               $('#postTweet').bind('click', function () {
                   var tweet = $('#tweetInput').val();
                   $.publish('tweet-posted', tweet);
               });
           }
       };
    }());
    

    For this approach there’s an excellent talk by Nicholas Zakas. For the MV* approach the best articles and books I know of are published by Addy Osmani.

    Drawbacks: You have to be careful about the excessive use of publish/subscribe. If you’ve got hundreds of events it can become very confusing to manage all of them. You may also have collisions if you’re not using namespacing (or not using it in the right way). An advanced implementation of Mediator which looks much like an publish/subscribe can be found here https://github.com/ajacksified/Mediator.js. It has namespacing and features like event “bubbling” which, of course, can be interrupted. Another drawback of publish/subscribe is the hard unit testing, it may become difficult to isolate the different functions in the modules and test them independently.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

My colleague and I are having a tough time deciding on a best practices
A colleague and I are having a bit of an argument over multiple inheritance.
A colleague of mine always sets their jQuery variables to null, to effectively dispose
A colleague once said that God is killing a kitten every time I write
A colleague mentioned that he heard about a lightweight collection which would automatically page
My colleague and I have been having a discussion about what Collections should be
A colleague of mine says that SQL Server saves the date and time of
A colleague came to me with a problem that I managed to answer but
I'm haiving an interesting discussion with an esteemed colleague and would like some additional
A colleague of mine wrote quite questionable piece of code some time ago, and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.