发布订阅JavaScript对象

    技术2022-07-11  154

    There are three keys to effective AJAX-driven websites:  event delegation, History management, and effective app-wide communication with pub/sub.  This blog employs of all of these techniques, and I thought I'd share the simplest of them:  a tiny pub/sub module I use on this site.

    有效的AJAX驱动网站有三个关键: 事件委托 , 历史记录管理以及与pub / sub进行有效的应用程序范围内的通信。 这个博客使用了所有这些技术,我想我将分享其中最简单的一种:我在本网站上使用的一个很小的发布/订阅模块。

    If you've not used pub/sub before, the gist is that you publish to a topic and anyone can subscribe, much like the way a radio works: a radio station broadcasts (publishes) and anyone can listen (subscribes).  This is excellent for highly modular web applications; it's a license to globally communicate without attaching to any specific object.

    如果您以前没有使用过pub / sub,则要点是您发布一个主题,任何人都可以订阅,就像广播的工作方式一样:广播电台广播(发布),任何人都可以收听(订阅)。 这对于高度模块化的Web应用程序非常有用; 这是在不附加任何特定对象的情况下进行全局通信的许可证。

    JavaScript (The JavaScript)

    The module itself is super tiny but massively useful:

    该模块本身很小,但是非常有用:

    var events = (function(){ var topics = {}; var hOP = topics.hasOwnProperty; return { subscribe: function(topic, listener) { // Create the topic's object if not yet created if(!hOP.call(topics, topic)) topics[topic] = []; // Add the listener to queue var index = topics[topic].push(listener) -1; // Provide handle back for removal of topic return { remove: function() { delete topics[topic][index]; } }; }, publish: function(topic, info) { // If the topic doesn't exist, or there's no listeners in queue, just leave if(!hOP.call(topics, topic)) return; // Cycle through topics queue, fire! topics[topic].forEach(function(item) { item(info != undefined ? info : {}); }); } }; })();

    Publishing to a topic:

    发布到主题:

    events.publish('/page/load', { url: '/some/url/path' // any argument });

    ...and subscribing to said topic in order to be notified of events:

    ...并订阅该主题,以便收到事件通知:

    var subscription = events.subscribe('/page/load', function(obj) { // Do something now that the event has occurred }); // ...sometime later where I no longer want subscription... subscription.remove();

    I use pub/sub religiously on this website and this object has done me a world of good.  I have one topic that fires upon each AJAX page load, and several subscriptions fire during that event (ad re-rendering, comment re-rendering, social button population, etc.).  Evaluate your application and see where you might be able to use pub/sub!

    我在该网站上虔诚地使用pub / sub,这个对象为我创造了一个美好的世界。 我有一个主题会在每次AJAX页面加载时触发,并且在该事件期间会触发多个订阅(广告重新渲染,评论重新渲染,社交按钮填充等)。 评估您的应用程序,看看您可以在哪里使用pub / sub!

    翻译自: https://davidwalsh.name/pubsub-javascript

    相关资源:JavaScript实现与使用发布/订阅模式详解
    Processed: 0.009, SQL: 9