Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
沐夕花开
eventBus
提交
2dcafeea
E
eventBus
项目概览
沐夕花开
/
eventBus
通知
1
Star
0
Fork
0
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
0
列表
看板
标记
里程碑
合并请求
0
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
E
eventBus
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
0
Issue
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
前往新版Gitcode,体验更适合开发者的 AI 搜索 >>
提交
2dcafeea
编写于
6月 14, 2022
作者:
沐夕花开
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
add .md
上级
6be9fb23
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
70 addition
and
0 deletion
+70
-0
eventBus.md
eventBus.md
+70
-0
未找到文件。
eventBus.md
0 → 100644
浏览文件 @
2dcafeea
![
1655191513242
](
https://tva2.sinaimg.cn/large/005YCUMZgy1h37sxe26ruj30hs0bc0t6.jpg
)
# 实现一个 EventBus
> EventBus 是一个事件总线,其应该具有事件订阅、发布、移除订阅的功能。
举个栗子:我订阅了一个事件A
`$on('A', function(){//当事件A触发时候我想做点什么})`
,订阅之后当发布A事件
`$emit('A')`
时,之前订阅传递进去的函数就会执行。当我不需要这个订阅时候可以取消
`$off('A')`
,之后在发布A事件
`$emit('A')`
时,就不会再执行订阅时的回调。
![
1655192401635
](
https://tvax1.sinaimg.cn/large/005YCUMZgy1h37tcv54sgj30us0fpdk4.jpg
)
完整代码:
```
js
class
EventBus
{
constructor
()
{
this
.
eventsCache
=
{}
this
.
uid
=
0
}
$on
(
key
,
callback
)
{
if
(
!
this
.
eventsCache
[
key
])
{
this
.
eventsCache
[
key
]
=
[]
}
const
uid
=
++
this
.
uid
this
.
eventsCache
[
key
].
push
({
uid
,
callback
})
return
uid
}
$emit
(
key
,
...
args
)
{
if
(
!
this
.
eventsCache
[
key
])
return
let
events
=
this
.
eventsCache
[
key
]
events
.
forEach
(
item
=>
{
item
.
callback
(...
args
)
if
(
item
.
isOnce
)
{
this
.
$off
(
key
,
item
.
uid
)
}
});
}
$off
(
key
,
uid
)
{
const
events
=
this
.
eventsCache
[
key
]
if
(
!
events
)
{
console
.
log
(
`事件
${
key
}
不存在`
)
return
}
if
(
!
uid
)
{
// 不传递uid,则清除当前 key 下所有的事件
delete
this
.
eventsCache
[
key
]
}
else
{
let
eventIdx
=
events
.
findIndex
(
item
=>
item
.
uid
===
uid
)
if
(
eventIdx
<
0
)
{
console
.
log
(
`事件
${
key
}
监听列表中不存在id为
${
uid
}
的回调`
)
return
}
// 移除当前uid的回调
events
.
splice
(
eventIdx
,
1
)
// 如果长度为0, 则移除
if
(
!
events
.
length
)
{
delete
this
.
eventsCache
[
key
]
}
}
}
$once
(
key
,
...
args
)
{
const
retId
=
this
.
$on
(
key
,
...
args
)
let
thisIdx
=
this
.
eventsCache
[
key
].
findIndex
(
item
=>
item
.
uid
===
retId
)
// 添加 isOnce 标记
this
.
eventsCache
[
key
][
thisIdx
].
isOnce
=
true
// 返回 uid
return
retId
}
}
const
eventBus
=
new
EventBus
()
export
default
eventBus
```
\ No newline at end of file
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录