手动封装观察者模式

//事件队列
const enentList={}
//封装监听 const $on
=function(eventName,callback){ if(!enentList[eventName]){ enentList[eventName]=[]; } enentList[eventName].push(callback); }
//封装发布 const $emit
=function(eventName,params){ if(enentList[eventName]){ var arr= enentList[eventName]; arr.forEach((cb)=>{ cb(params) }) } }
//封装解绑 const $off
=function(eventName,callback){ if(enentList[eventName]){ if(callback){ var index= enentList[eventName].indexOf(callback); enentList[eventName].splice(index,1); }else{ enentList[eventName].length=0; } } } export default{ $on, $emit, $off }

 测试一下

function fn1(params){
    console.log(111,params);
}
function fn2(params){
    console.log(222,params);
}
function fn3(params){
    console.log(333,params);
}
//测试一
$on("handler",fn1);
$on("handler",fn2);
$on("handler",fn3);
$emit(fn1,'aaa')
//运行node 文件名
//结果:
111,aaa
222,aaa
333,aaa

//测试二
$on("handler",fn1);
$on("handler",fn2);
$on("handler",fn3);
$off("handler")
$emit(fn1,'aaa')
//运行node 文件名
//解绑所有,所以运行时不会显示结果

//测试三
$on("handler",fn1);
$on("handler",fn2);
$on("handler",fn3);
$off("handler",fn1)
$emit(fn1,'aaa')
//运行node 文件名
//解绑了fn1,所以运行时显示结果
222,aaa
333,aaa
原文地址:https://www.cnblogs.com/liuXiaoDi/p/12302410.html