观察者模式,主要有三个部分,注册监听,删除监听,发送监听。
class obServe{
public eventObj:Object = new Object;
constructor(){
this.eventObj = {};
}
//注册监听
public addMonitor(_eventType,_fun){
if(!this.eventObj.hasOwnProperty(_eventType){
this.eventObj[_eventType] = [];
}
if(_fun == "function"){
this.eventObj[_eventType].push(_fun);
}
}
// 删除监听
public removeMonitor(_eventType){
if(this.eventObj.hasOwnProperty(_eventType){
delete this.eventObj[_eventType];
}
}
// 发送监听
public sendMonitor(_eventType,..._args){
if(this.eventObj.hasOwnProperty(_eventType){
for(let key in this.eventObj[_eventType]){
if(typeof f == "function"){
f.apply(_args);
}
}
}
}
}
// 实例化对象,方便调用
class newObj{
public static e:obServe = new obServe;
}
应用:
// 当监听到有test类型的时候,触发函数setTestFun
newObj.e.addMonitor("test",setTestFun);
// 移除
newObj.e.removeMonitor("test",setTestFun);
// 发送监听
newObj.e.sendMonitor("test");
setTestFun(){
console.log("我接收到数据了----")
}
// 我接收到数据了----
第一次写观察者模式,如果有什么不对,或者需要优化的地方,欢迎指出。