mitt.js

-

最近项目上用了一个自己写的emitter.js;

发现off解绑回调的时候出了问题,off方法是把回调函数转换成字符串对比,如果相同,则去除发射器中的回调;但是我在很多组件中传入的方法几乎一样,于是奇怪的事情发生了;

emitter无缘无故的不触发,经过一番调试,发现是以上原因;于是找了一个插件mitt.js;(其实是vue2中的$bus);

文档地址:https://www.npmjs.com/package/mitt

安装:

npm install --save mitt

引入

// using ES6 modules
import mitt from 'mitt'

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

也可以不用下载插件,之间把源码拿过来,替换自己的emitter.js

function mitt (n) {
  return {
    all: n = n || new Map,
    on: function (e, t) {
      var i = n.get(e);
      i ? i.push(t) : n.set(e, [t])
    },
    off: function (e, t) {
      var i = n.get(e);
      i && (t ? i.splice(i.indexOf(t) >>> 0, 1) : n.set(e, []))
    },
    emit: function (e, t) {
      var i = n.get(e);
      i && i.slice().map(function (n) {
        n(t)
      }), (i = n.get("*")) && i.slice().map(function (n) {
        n(e, t)
      })
    }
  }
};

const emitter = new mitt();
export default emitter;

 用法

// 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

 

 

-

posted @ 2022-03-30 20:07  古墩古墩  Views(945)  Comments(0Edit  收藏  举报