// 事件派发 监听和回调管理
class Bus {
constructor() {
this.callbacks = {}
}
$on (name, fn) {
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
$emit (name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach(cb => cb(args))
}
}
}
// main.js
Vue.prototype.
b
u
s
=
n
e
w
B
u
s
(
)
/
/
c
h
i
l
d
1
t
h
i
s
.
bus = new Bus() // child1 this.
bus=newBus()//child1this.bus.
o
n
(
′
f
o
o
′
,
h
a
n
d
l
e
C
l
i
c
k
)
/
/
c
h
i
l
d
2
t
h
i
s
.
on('foo', handleClick) // child2 this.
on(′foo′,handleClick)//child2this.bus.$emit(‘foo’)