Giter VIP home page Giter VIP logo

yxmsg's Introduction

YxMsg

一个使用TypeScript编写的轻量级发布订阅模式库、支持消息优先级。

特性

  • 无任何依赖
  • 轻量级
  • 支持消息优先级

安装

请确保已安装Nodejs环境

npm

npm i yxmsg

yarn

yarn add yxmsg

pnpm

pnpm add yxmsg

使用

// 导入YxMsg
import { YxMsg } from "yxmsg";
// 创建YxMsg实例
const message = new YxMsg();

// 定义消息处理函数
const handler = (data: string) => {
  console.log(data);
};
// 注册消息
message.on("test", handler);

// 发射消息
message.emit("test", "Hello World!");

// 注销消息
message.off("test", handler);

注册消息

// 注册消息
message.on("test", handler);
// 注册消息会返回一个消息id, 可用于注销消息
const id = message.on("test", handler);
// 通过id注销消息
message.off("test", id);

// 注册消息时可以绑定target
const target = {};
message.on("test", handler, target);

// 注册消息时可以设置消息优先级 优先级越高 越先执行
// 优先级默认为0
message.on("test", handler, null, 1); // 优先级为1
message.on("test", handler, null, 2); // 优先级为2
message.on("test", handler, target, 3); // 优先级为3

发送消息

// 发射消息
message.emit("test", "Hello World!");
// 发射消息可以携带多个参数
message.emit("test1", "Hello World!", 123, { a: 1, b: 2 });

注销消息

// 注销消息
message.off("test", handler);
// 如果消息注册时绑定了target, 则需要传入target才可以注销
message.off("test", handler, target);

// 通过消息id注销消息
message.off("test", id);
// 注销指定消息类型的所有消息
message.off("test");

yxmsg's People

Contributors

yxdtg avatar

Watchers

 avatar

Forkers

liangxudongsun

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.