var Dispatch={
keys:{},
//订阅,同一个key可以订阅多个不同的函数
subscribe:function(key, fn, context){
if(!this.keys[key]){
this.keys[key]=[]
}
this.keys[key].push({fn, context:context});
},
// 触发某个通知
notifyObs: function(key,params){
let fns = this.keys[key] || [];
if(!fns ||fns.length===0){
return false;
}
for(let i =0; i<fns.length; i++){
let {fn, context} = fns[i];
fn.call(context, params)
}
},
// // 广播通知所有
// broadcast: function(){
// let keys= this.keys;
// Object.keys(keys).forEach(item=>{
// let {fn, context} = keys[item];
// fn.call(context)
// })
// }
}
function Student(name){
this.name = name
}
s = new Student("lhf");
Student.prototype.study=function(param){
console.log("myname is ", this.name)
console.log("study", param)
}
jack = new Student("jack");
Dispatch.subscribe("study", jack.study, jack)
// 订阅
Dispatch.subscribe("study", s.study, s)
Dispatch.notifyObs("study", {type:"notice", num:1})
网友评论