• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • Tiny Publish-Subscribe implementation in jQuery

    Blogs20172017-04-21


    Tiny Publish-Subscribe implementation in jQuery

    Very helpful article: jQuery Tiny Pub/Sub: A really, really, REALLY tiny pub/sub implementation for jQuery.

    (function($) {
      var o         = $({});
      $.subscribe   = o.on.bind(o);
      $.unsubscribe = o.off.bind(o);
      $.publish     = o.trigger.bind(o);
    }(jQuery));

    The $.subscribe, $.unsubscribe and $.publish methods all use the jQuery .on(), .off() and .trigger() methods internally.

    Just use this handy terminology guide (jQuery events term → Pub/Sub term), and everything should make sense:

    • on → subscribe
    • off → unsubscribe
    • trigger → publish
    • type → topic

    More examples:

    function handle(e, a, b, c) {
      // `e` is the event object, you probably don't care about it.
      console.log(a + b + c);
    };
    
    $.subscribe("/some/topic", handle);
    
    $.publish("/some/topic", [ "a", "b", "c" ]);
    // logs: abc
    
    $.unsubscribe("/some/topic", handle); // Unsubscribe just this handler
    
    // Or:
    
    $.subscribe("/some/topic", function(e, a, b, c) {
      console.log(a + b + c);
    });
    
    $.publish("/some/topic", [ "a", "b", "c" ]);
    // logs: abc
    
    $.unsubscribe("/some/topic"); // Unsubscribe all handlers for this topic