背景
業務のコードでpubsubjsを初めて知った為です。
pubsubjsとは
JavaScriptで書かれたトピックベースのpub/subパターンのライブラリです。
pubsubパターンについては以下の記事で紹介していますのでご覧ください。
トピックというのは以下のようなtypeのことを言うそうです。
type Message {
type: "TYPE";
data: Data;
}
トピックを使うことでメッセージ配信先をコントロールできます。
pubsubjsを使ってみる
install
npm i pubsub-js
npm i @types/pubsub-js
基本的な例
index.ts
import PubSub from 'pubsub-js';
const MY_TOPIC = 'hello';
PubSub.subscribe(MY_TOPIC, function (msg, data) {
console.log(data)
});
PubSub.publish(MY_TOPIC, 'world');
world
トピックにはtypo対策の為に文字列リテラルではなく「定数」を使用することを推奨されています
購読をキャンセル
以下は2回world
が表示されます。
import PubSub from "pubsub-js";
const MY_TOPIC = "hello";
PubSub.subscribe(MY_TOPIC, function (msg, data) {
console.log(data);
});
PubSub.publish(MY_TOPIC, "world");
PubSub.publish(MY_TOPIC, "world");
world
world
以下のようにsubscribe
メソッドの返り値のtoken
をPubSub.unsubscribe(token)
に渡すと2回目以降の購読をキャンセルできます。
import PubSub from "pubsub-js";
const MY_TOPIC = "hello";
const token = PubSub.subscribe(MY_TOPIC, function (msg, data) {
console.log(data);
// unsubscribe this subscriber from this topic
PubSub.unsubscribe(token);
});
PubSub.publish(MY_TOPIC, "world");
PubSub.publish(MY_TOPIC, "world");
world
階層的なトピックによって配信内容を分ける
import PubSub from "pubsub-js";
const TOPIC = {
PARENT: "parent",
CHILD: "parent.child",
ANCESTOR: "parent.child.ancestor",
};
PubSub.subscribe(TOPIC.PARENT, function (msg, data) {
console.log("subscribe_parent", data);
});
PubSub.subscribe(TOPIC.CHILD, function (msg, data) {
console.log("subscribe_child:", data);
});
PubSub.subscribe(TOPIC.ANCESTOR, function (msg, data) {
console.log("subscribe_ancestor:", data);
});
PubSub.publish(TOPIC.ANCESTOR, "ancestor");
subscribe_ancestor: ancestor
subscribe_child: ancestor
subscribe_parent ancestor
parent
にドットで繋げて記述することでparent
→parent.child
→parent.child.ancestor
が親子孫の関係になります。
subscribeのcallbackは最下層から呼び出されます。
最後に
pubsubjsはまだ他にも機能はありますが、概要は掴めました。
イベントリスナーで使われていたので今度は実際にどんな場面で使われているか実装したいと思います。
参考