用原生EventTarget取代EventBus(mitt)可好?
Author:zhoulujun Date:
vue3取消了vue2里面的EventBUS,建议使用https://github.com/developit/mitt/
mport mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', 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
代码也很简单
https://github.com/developit/mitt/blob/main/src/index.ts
但是,如过只是简单的需求,用JS原生的岂不是更好
EventTarget
https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget
该接口主要提供三个实例方法。
addEventListener:绑定事件的监听函数
removeEventListener:移除事件的监听函数
dispatchEvent:触发事件
具体可以看 阮一峰 老师的教程:https://www.bookstack.cn/read/javascript-tutorial/docs-events-eventtarget.md
转载本站文章《用原生EventTarget取代EventBus(mitt)可好?》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/js/2022_0923_9275.html
下一篇:最后一页