Giter VIP home page Giter VIP logo

pubsub's Introduction

pubsub

使用 typescript 开发的事件订阅/发布,支持事件名和事件参数类型描述。

安装

pnpm install @redchili/pubsub

Live Demo

示例

基本使用方式

import PubSub, { Subscriber } from '@redchili/pubsub';

// 定义事件和事件传递的数据类型
interface EventType {
  click: { value: string };
}

const pubsub = new PubSub<EventType>();

// 订阅者实例,用于订阅和解除订阅
const subscriber = new Subscriber();

// subscriber 订阅 click 事件
pubsub.subscribe('click', subscriber, (event) => {
  console.log(event.value);
});

// 发布 click 事件
pubsub.publish('click', { value: 'click event' });

// 取消 subscriber 的所有订阅
pubsub.unsubscribe(subscriber);

取消某个事件的所有订阅

pubsub.unsubscribe('click');

取消订阅者的所有订阅

pubsub.unsubscribe(subscriber);

取消全部订阅

pubsub.unsubscribe();

其他

定义不传递参数的事件

interface EventType {
  reset: undefined;
}

const pubsub = new PubSub<EventType>();

pubsub.publish(reset, undefined);

在 React-Native 中使用

本项目使用了 nanoid 作为事件回调函数唯一 ID,所以在 React-Native 中使用请先安装 nanoid 的使用指南配置 polyfill 库,具体参考如下: https://github.com/ai/nanoid/blob/main/README.zh-CN.md#react-native

pubsub's People

Contributors

xiamu14 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.