@@ -6,25 +6,25 @@ function createEventBus() {
66// 只有_内部函数才能操作 listeners
77// 在内部用于添加回调函数的工具函数
88// 通过单调递增的 id 确保不会因为删除而有重复 id
9- createEventBus . prototype . _add = ( event , handler , once ) => {
9+ createEventBus . prototype . _add = function ( event , handler , once ) {
1010 if ( ! this . listeners . has ( event ) ) { // 初始化
1111 this . listeners . set ( event , [ 0 ] )
1212 }
1313 const pre = this . listeners . get ( event )
1414 const newId = pre [ 0 ] + 1
1515 const curObj = {
1616 id : newId ,
17- handler : ( ) => handler ( ) ,
18- flag : once // 是否只执行一次就移除
17+ handler : handler ,
18+ once : once // 是否只执行一次就移除 // 注意变量名的统一
1919 }
20- const new = [ ...pre , curObj ]
21- new [ 0 ] = newId
22- this . listeners . set ( event , new )
20+ const newVal = [ ...pre , curObj ]
21+ newVal [ 0 ] = newId
22+ this . listeners . set ( event , newVal )
2323 return newId // 返回 newId 用于删除
2424}
2525
2626// 在内部用于删除回调函数的工具函数
27- createEventBus . prototype . _delete = ( event , id ) => {
27+ createEventBus . prototype . _delete = function ( event , id ) {
2828 const cur = this . listeners . get ( event )
2929 if ( cur [ 0 ] < id ) return false // 如果最大的 id 都比当前输入的小,那么肯定输错了
3030 let targetIdx = - 1
@@ -34,9 +34,10 @@ createEventBus.prototype._delete = (event, id) => {
3434 break
3535 }
3636 }
37+ // 或者用 .filter 筛除
3738 if ( targetIdx === - 1 ) return false
38- const new = cur . splice ( targetIdx , 1 )
39- this . listeners . set ( event , new )
39+ cur . splice ( targetIdx , 1 )
40+ this . listeners . set ( event , cur )
4041 return true // 删除成功
4142}
4243
@@ -54,8 +55,11 @@ createEventBus.prototype.once = function (event, handler) {
5455
5556createEventBus . prototype . emit = function ( event , ...args ) {
5657 const arr = this . listeners . get ( event )
57- for ( const item of arr ) {
58- item . handler ( args )
58+ if ( ! arr ) return // 防空处理
59+ // for (const item of arr) {
60+ for ( let i = 1 ; i < arr . length ; i ++ ) { // 注意[0]存储的是ID
61+ const item = arr [ i ]
62+ item . handler ( ...args ) // 注意传参
5963 if ( item . once ) {
6064 this . _delete ( event , item . id )
6165 }
@@ -65,3 +69,8 @@ createEventBus.prototype.emit = function (event, ...args) {
6569// 只有_内部函数才能操作 listeners
6670// 在内部用于添加回调函数的工具函数
6771// 通过单调递增的 id 确保不会因为删除而有重复 id
72+
73+
74+ const bus = new createEventBus ( )
75+ bus . on ( 'click' , name => console . log ( `你好 ${ name } ` ) )
76+ bus . emit ( 'click' , 'ceilf6' )
0 commit comments