📜 ⬆️ ⬇️

Pub / Sub JavaScript object

Translation of the article "Pub / Sub JavaScript Object" by David Walsh

There are three techniques for writing AJAX websites: event delegation , history management, and pub / sub communication at the application level. I use all three techniques and I would like to share with you the simplest of them: the tiny pub / sub module that I use on my website.

If you do not know what pub / sub is, then the point is that you publish in a certain topic (topic), and anyone can subscribe to it. This is similar to how the radio works: the radio station broadcasts (publishes) and everyone can listen (subscribe). This is an excellent approach for modular web applications; it is a way of global communication without being tied to any particular object.

Javascript


The module itself is very tiny, but very useful:
var events = (function(){ var topics = {}; return { subscribe: function(topic, listener) { //   topic,     if(!topics[topic]) topics[topic] = { queue: [] }; //  listener   var index = topics[topic].queue.push(listener) -1; //     return { remove: function() { delete topics[topic].queue[index]; } }; }, publish: function(topic, info) { //       ,    if(!topics[topic] || !topics[topic].queue.length) return; //       var items = topics[topic].queue; items.forEach(function(item) { item(info || {}); }); } }; })(); 

We publish in the subject:
 events.publish('/page/load', { url: '/some/url/path' //   }); 

... subscribe to the topic to receive event notifications:
 var subscription = events.subscribe('/page/load', function(obj) { //  -,    }); // ...      ... subscription.remove(); 

I scrupulously use pub / sub religiously on my website, and this object has done me a lot of good. I have a theme for loading the page via AJAX and several subscriptions that are triggered during this event (redrawing ads, comments, social icons, etc.). Check where in your application you can use pub / sub!

')

Source: https://habr.com/ru/post/229589/


All Articles