手写一个订阅发布者模式

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{
//             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})

你可能感兴趣的:(手写一个订阅发布者模式)