zoukankan      html  css  js  c++  java
  • 使用pubsub-js来做消息的订阅和发布

    安装pubsub-js

    • 使用npm安装:npm install pubsub-js
    • 使用yarn安装:yarn add pubsub-js

    引入

    import PubSub from 'pubsub-js'
    
    // or when using CommonJS
    const PubSub = require('pubsub-js');
    

    基本案例

    // create a function to subscribe to topics
    var mySubscriber = function (msg, data) {
        console.log( msg, data );
    };
    
    // add the function to the list of subscribers for a particular topic
    // we're keeping the returned token, in order to be able to unsubscribe
    // from the topic later on
    var token = PubSub.subscribe('MY TOPIC', mySubscriber);
    
    // publish a topic asynchronously
    PubSub.publish('MY TOPIC', 'hello world!');
    
    // publish a topic synchronously, which is faster in some environments,
    // but will get confusing when one topic triggers new topics in the
    // same execution chain
    // USE WITH CAUTION, HERE BE DRAGONS!!!
    PubSub.publishSync('MY TOPIC', 'hello world!');
    

    取消订阅

    // create a function to receive the topic
    var mySubscriber = function (msg, data) {
        console.log(msg, data);
    };
    
    // add the function to the list of subscribers to a particular topic
    // we're keeping the returned token, in order to be able to unsubscribe
    // from the topic later on
    var token = PubSub.subscribe('MY TOPIC', mySubscriber);
    
    // unsubscribe this subscriber from this topic
    PubSub.unsubscribe(token);
    

    取消某个函数的所有订阅

    // create a function to receive the topic
    var mySubscriber = function(msg, data) {
        console.log(msg, data);
    };
    
    // unsubscribe mySubscriber from ALL topics
    PubSub.unsubscribe(mySubscriber);
    

    取消某个topic的全部订阅

    PubSub.subscribe('a', myFunc1);
    PubSub.subscribe('a.b', myFunc2);
    PubSub.subscribe('a.b.c', myFunc3);
    
    PubSub.unsubscribe('a.b');
    // no further notifications for 'a.b' and 'a.b.c' topics
    // notifications for 'a' will still get published
    

    取消所有订阅

    PubSub.clearAllSubscriptions();
    // all subscriptions are removed
    
  • 相关阅读:
    linux 加载模块时出现cannot insert '*.ko': Device or resource busy错误
    Beej's Guides [Share]
    linux 符号链接与硬链接的区别
    Source Insight 3.5 一直刷新问题
    linux 内核线程与普通进程的区别
    为明远智睿 imx6q Demo v2.5 添加spi5的支持
    linux dereferencing pointer to incomplete type错误
    imx6 ECSPI Config Register 中SS_CTL的使用
    linux Copy-on-Write
    C语言根据国家英文首字母进行排序
  • 原文地址:https://www.cnblogs.com/pangqianjin/p/14756726.html
Copyright © 2011-2022 走看看