发布订阅模式有4个方法,存储结构是一个对象键是表示类一类,值是一个对象,每一项都是一个方法
1.on方法将某给对象属性,数组添加一个方法
2.emit方法将对象属性的数组中的方法遍历执行
3.off删除对象属性数组中的某一个方法
4.once和on一样,只是添加的方法emit只能执行一次,执行一次后销毁
(function (){
interface EventFace {
// 定义类
on: (TypeName: string, callback: Function) => void; //订阅消息
emit: (TypeNam: string, ...args: Array<any>) => void; // 发布消息
off: (TypeName: string, callback: Function) => void; //删除指定函数
once(TypeName: string, callback: Function): void; // 只执行一次,删除指定函数
//on(Ms:string,Fun:Function):void 接口定义函数
}
// 定义对象 { name:[fun1,fun2],name2:[fun3,fun4]}
interface List {
[index: string]: Array<Function>;
}
class Dispatch implements EventFace {
// public list: List = {};
public list: List;
constructor() {
this.list = {};
}
on(TypeName: string, callback: Function): void {
this.list[TypeName];
const callbackList: Array<Function> = this.list[TypeName] || [];
callbackList.push(callback);
this.list[TypeName] = callbackList;
} //订阅消息
emit(TypeNam: string, ...args: Array<any>): void {
if(TypeNam && args)
{
this.list[TypeNam]?.forEach(fun=>{
// 执行全部
fun.apply(this,args)
})
}
else
{
console.log("参数错误")
}
} // 发布消息
off(TypeName: string, callback: Function): void {
if(TypeName && callback)
{
let index:number=this.list[TypeName]?.indexOf(callback)
console.log(index)
if(index>-1)
{
this.list[TypeName]?.splice(index,1)// 返回删除的元素
}
else
{
console.log("没找到这个函数")
}
}else
{
console.log("参数错误")
}
} //解除绑定
once(TypeName: string, callback: Function): void {
if(TypeName && callback)
{
// 和on一样,只是它添加的只能使用一次
let decor=(...args:Array<any>)=>
{
callback.apply(this,args)// 执行然后删除
this.off(TypeName,decor)// 删除方法
}
// 使用on添加到,list中
this.on(TypeName,decor);
}else
{
console.log("参数错误")
}
} // 只执行一次
}
let o=new Dispatch()
function fun1(...args:Array<any>)
{
console.log("fun1-1",args)
}
o.on("fun1",fun1);// 订阅
o.emit("fun1",12,3,5) ///
o.off("fun1",fun1)
o.emit("fun1",12,3) ///
function fun2(...arge:Array<any>)
{
console.log("fun2",arge)
}
o.once("fun2",fun2)
o.emit("fun2",12,3,2) ///
o.emit("fun2",12,3,2) ///
})()