美文网首页
Vue3.x mitt.js 发布-订阅模式库

Vue3.x mitt.js 发布-订阅模式库

作者: small_zeo | 来源:发表于2023-09-17 14:16 被阅读0次

mitt API方法有:

  • on 订阅事件
  • emit 发布事件
  • off 取消订阅的事件

Install

$ npm install --save mitt

// using ES6 modules
import mitt from 'mitt'

// using CommonJS modules
var mitt = require('mitt')

用法

import mitt from 'mitt'

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// clearing all events
emitter.all.clear()

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten

Typescript

import mitt from 'mitt';

type Events = {
  foo: string;
  bar?: number;
};

const emitter = mitt<Events>(); // inferred as Emitter<Events>

emitter.on('foo', (e) => {}); // 'e' has inferred type 'string'

emitter.emit('foo', 42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'. (2345)

// or

import mitt, { Emitter } from 'mitt';

type Events = {
  foo: string;
  bar?: number;
};

const emitter: Emitter<Events> = mitt<Events>();

相关文章

  • 发布订阅模式(观察者模式)

    发布订阅模式(观察者模式) 发布订阅也叫观察者模式 发布 && 订阅 使用

  • 设计模式之发布订阅模式(1) 一文搞懂发布订阅模式

    目录 发布/订阅者模式的优点 实现发布/订阅者模式需要考虑的点 何时应使用发布/订阅者模式 发布/订阅者模式与观察...

  • JS-简单实现发布订阅模式

    发布订阅模式主要涉及三个对象:发布者、订阅者、主题对象。 发布-订阅模式 定义  发布-订阅模式又称观察者模式,它...

  • 从发布-订阅模式到消息队列

    发布-订阅模式 发布-订阅模式又称为观察者模式(网上也有很多说这两种模式区别,个人觉得区别不大),在发布-订阅模式...

  • MQTT 5.0 - 发布订阅模式介绍

    MQTT 协议的核心在于发布订阅模式,在本文中,我们将对这一模式进行深入的介绍。 发布订阅模式 发布订阅模式区别于...

  • Redis发布订阅模式

    Redis支持发布订阅模式,先了解一下与发布订阅相关的命令。 发布订阅模式命令 SUBSCRIBE命令用于订阅ch...

  • MQTT 发布/订阅模式介绍

    MQTT 发布/订阅模式 发布订阅模式(Publish-Subscribe Pattern)是一种消息传递模式,它...

  • 观察者模式&&订阅发布模式

    观察者模式&&订阅发布模式 参考:知乎-观察者模式 vs 发布订阅模式[https://zhuanlan.zhih...

  • 32.Eventbus用法

    前言 EventBus是greenrobot在Android平台发布的一款以订阅——发布模式为核心的开源库。Eve...

  • EventBus源码解析

    简单的使用 EventBus是greenrobot在Android平台发布的一款以订阅——发布模式为核心的开源库。...

网友评论

      本文标题:Vue3.x mitt.js 发布-订阅模式库

      本文链接:https://www.haomeiwen.com/subject/pyqwvdtx.html