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);
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
原文:https://www.cnblogs.com/pangqianjin/p/14756726.html