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>();