简单的订阅发布功能
class MyDispatch {
constructor() {
this._dispatch_list = []
}
register_on(id, command_type, func) { // 注册事件
const dispatch_obj = { id, command_type, func: func }
this._dispatch_list.push(dispatch_obj)
}
register_off(id) { // 移除事件
this._dispatch_list = this._dispatch_list.filter(item => item.id !== id)
}
dispatch(command_type, data) { // 触发并执行事件,根据command_type区分类型
for (let i = 0; i < this._dispatch_list.length; i++) {
const dispatch_obj = this._dispatch_list[i]
if (command_type === dispatch_obj.command_type) {
dispatch_obj.func(data)
}
}
}
}
// 混入的代码
function testA(emits) {
const data = '执行成功咯!'
emits.dispatch('do', data)
}
// 组件代码
function mainTest() {
const emits = new MyDispatch()
emits.register_on('testB', 'do', testB)
testA(emits)
function testB(data) {
console.log('testB 执行,', data)
}
}
mainTest()
运行结果
this绑定
function testA() {
const data = '执行成功咯!'
const testB = this.testB
if (testB) {
testB(data)
}
}
function mainTest() {
const thisArg = {
testB: testB
}
testA.call(thisArg)
function testB(data) {
console.log('testB 执行,', data)
}
}
mainTest()
执行结果同上