Coder Social home page Coder Social logo

oh-my-mitt's Introduction

oh-my-mitt

组件间通信简单实现。

特征

  • 体积小,无依赖 📦
  • 兼容多种模块方案 ⏱️

类型定义

export interface IEventHandler {
  (...rest: any[]): any
}

interface IEventMap {
  [eventType: string]: Array<{
    type: string;
    cb: IEventHandler;
    options?: {
      once?: boolean;
    }
  }>
}

使用

安装

pnpm/yarn/npm install oh-my-mitt

引入

import mitter from 'oh-my-mitt'

方法

on(type: string, cb: IEventHandler)

监听 type 事件,并触发回调 cb 。同一回调,多次注册时,仅能成功注册一次,避免了多次执行。

mitter.on('show', () => {
  console.log('show')
})
// 多次触发,'show' 打印多次

once(type: string, cb: IEventHandler)

监听 type 事件,并触发回调 cb,与 on 方法不同的是,只监听一次

mitter.once('show', () => {
  console.log('show')
})
// 多次触发,'show' 只打印 1 次

emit(type: string, payload?: any, cb?: IEventHandler)

触发 type 事件,可选参数传递值 payload 可选参数执行回调 cb

mitter.emit('show')

off(type: string, cb?: IEventHandler)

移除对 type 事件的监听,可选参数传递值 cb,有两种传递情况:

  • 若无 cb 参数,则抹除掉所有侦听 type 的事件;
  • 若有 cb 参数,则只抹除掉对该 cb 回调的侦听事件;
const openDialog = () => {
  console.log('打开弹窗')
}
mitter.off('show') // 彻底不再侦听 `show` 事件
mitter.off('show', openDialog) // 仅仅不再执行 `show` 事件下 openDialog 的回调

oh-my-mitt's People

Contributors

hdusy avatar

Watchers

 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.