Three kill servers of efficient AJAX websites: Event proxy, browsing history management, and efficient application-level publishing/subscription communication mechanism. the original site of this blog uses these three technologies at the same time. In this article, the author will share one of the simplest ones: a micro-publishing/subscription module used by the website.
If you do not know the publishing/subscription mode, you can share it with you by posting a blog post. Everyone can subscribe to your blog, similar to the way radio stations work: there is a platform for broadcasting (publishing, publishes). Anyone else can listen (subscribes ). This mode is excellent for highly modular applications. It is a key for global communication and does not need to depend on a special object.
JavaScript implementation
This module is very simple and powerful:
Var events = (function () {var topics = {}; return {subscribe: function (topic, listener) {// if not, create a topic object if (! Topics [topic]) topics [topic] = {queue: []}; // Add the listener to the queue var index = topics [topic]. queue. push (listener)-1; // provides the handle (object) for removing a topic. return (function (topic, index) {return {remove: function () {delete topics [topic]. queue [index] ;}}) (topic, index) ;}, publish: function (topic, info) {// if the topic does not exist, or the queue does not have a listener, return if (! Topics [topic] |! Topics [topic]. queue. length) return; // trigger an event by looping the topics queue! Var items = topics [topic]. queue; items. forEach (function (item) {item (info || {});});}};})();
Example:
Publish a topic:
Events. publish ('/page/load', {url:'/some/url/path' // This can be any object, any parameter });
Subscribe to topics to receive Event Notifications:
Var subtasks = events. subscribe ('/page/load', function (obj) {// when an event occurs, you can perform some operations ...}); //... if you do not want to continue the subscription after some operations are completed, remove the subscription... subtasks. remove ();
The original author used the publish/subscribe mode in a large amount on the blog site, and the actual user experience is also very good.
When an AJAX page is loaded, a topic is published, and the event triggers responses from multiple subscribers (for example, reload ads, refresh comments, and associate the share button ). we recommend that you evaluate your website to see where the pub/sub mode can be used.