npm 包地址
github 包地址
pubsub-js
是一个轻量级的 JavaScript
基于主题的消息订阅发布库 ,压缩后小于1b。它具有使用简单、性能高效、支持多平台等优点,可以很好地满足各种需求。
你可以通过以下几种方式获取 pubsub-js
。
首先,你需要在项目根目录下使用以下命令安装 pubsub-js
:
# 使用 pnpm 安装
pnpm add pubsub-js
# 使用 npm 安装
npm install --save pubsub-js
# 使用 yarn 安装
yarn add pubsub-js
你还可以通过 CDN
获取构建好的 pubsub-js
文件。将以下代码添加到 HTML
文件的 标签中:
<script src="https://unpkg.com/pubsub-js">script>
<script src="http://www.jsdelivr.com/#!pubsubjs">script>
<script src="https://cdnjs.com/libraries/pubsub-js">script>
GitHub下载地址
截止到目前,获取的最新版本是 v1.9.4
,如图:
在 JavaScript
文件顶部使用 import
引入 pubsub-js
:
// using ES6 modules
import PubSub from 'pubsub-js'
// using CommonJS modules
const PubSub = require('pubsub-js')
script
标签引入通过直接在 HTML
文件中添加 标签,引入构建好的
pubsub-js
文件:
DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/pubsub-js">script>
head>
html>
以更新未读消息数量为例。
pubsub.js
文件import PubSub from 'pubsub-js'
export default PubSub
subscribe
订阅事件/ unsubscribe
取消订阅import { onMounted, onUnmounted, ref } from 'vue'
import PubSub from '@/utils/pubsub'
const count = ref(0)
const readmessage = () => {
count.value = count.value - 1
}
onMounted(() => {
PubSub.subscribe('messageread', readmessage)
...
})
onUnmounted(() => {
PubSub.unsubscribe('messageread', readmessage)
})
publish
发送消息import PubSub from '@/utils/pubsub'
...
PubSub.publish('messageread')
...
// subscriptions by token from all topics
PubSub.getSubscriptions('token');
// count by token from all topics
PubSub.countSubscriptions('token');
订阅之后,一定要取消订阅。
// 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);
// no further notifications for 'a.b' and 'a.b.c' topics
// notifications for 'a' will still get published
PubSub.subscribe('a', myFunc1);
PubSub.subscribe('a.b', myFunc2);
PubSub.subscribe('a.b.c', myFunc3);
PubSub.unsubscribe('a.b');
// all subscriptions are removed
PubSub.clearAllSubscriptions();
pubsub-js
通过发布/订阅模式实现实现组件间的解耦合,可以减少代码的复杂度和维护成本,使代码设计更人性化。