0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

pubsubjsを使ってみる

Last updated at Posted at 2024-10-17

概要

pubsubjsとは

  • JavaScriptで書かれたトピックベースのpub/subパターンのライブラリです
  • トピックを使うことでメッセージ配信先をコントロールできます
  • 一階層しかないトピック以外にも階層的なトピックによって配信内容を分けることができます

背景

業務のコードで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メソッドの返り値のtokenPubSub.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にドットで繋げて記述することでparentparent.childparent.child.ancestorが親子孫の関係になります。

subscribeのcallbackは最下層から呼び出されます。

最後に

pubsubjsはまだ他にも機能はありますが、概要は掴めました。
イベントリスナーで使われていたので今度は実際にどんな場面で使われているか実装したいと思います。

参考

所属企業に興味ある方は以下ご覧ください!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?