发布订阅

 1 <script type="text/javascript">
 2 //发布 emit  订阅 on {女生失恋:['哭','购物','吃']}
 3 function Girl(){
 4     this._events = {}
 5 }
 6 Girl.prototype.on = function(eventName,callback){
 7     if(this._events[eventName]){//不是第一次
 8         this._events[eventName].push(callback); //{失恋:[cry,eat,shopping]}
 9     }else{
10         this._events[eventName] = [callback]; //{失恋:[cry]}
11     }
12 };
13 Girl.prototype.emit = function(eventName,...args){//用剩余运算符[我,你,他],在参数里叫剩余运算符
14     //[].slice.call(arguments,1);都不理想
15     //Array.from(arguments).slice(1);
16     if(this._events[eventName]){
17         //this._events[eventName].forEach(cb=>cb(...args));//在其他地方叫展开运算符
        for(let i=0;i<args.length;i++){
          this._events[eventName].forEach(item=>item(args[i]));
        }
18 //this._events[eventName].forEach(cb=>cb.apply(this,args)); 19 } 20 }; 21 let girl = new Girl(); 22 let cry = (who)=>{console.log(who + '哭');}; 23 let shopping = (who)=>{console.log(who + '购物');}; 24 let eat = (who)=>{console.log(who + '吃');}; 25 girl.on('失恋',cry);//{失恋:[cry]} 26 girl.on('失恋',eat);//{失恋:[cry,eat]} 27 girl.on('失恋',shopping);//{失恋:[cry,eat,shopping]} 28 29 girl.emit('失恋','我','你'); 30 31 //一对多 32 //{a:[fn,fn,fn]} 33 </script>
let events = {
    _events:[],
    on(fn){
        this._events.push(fn);
    },
    emit(data){
        this._events.forEach((event)=>{
            event(data);
        });
    }
};
let arr = [];

events.on((data)=>{
    arr.push(data);
    console.log(data)
});

events.on(()=>{
    if(arr.length === 2){
        console.log('老子不舔了')
    }
});
setTimeout(()=>{
    events.emit('第一次舔');
},1000);
setTimeout(()=>{
    events.emit('第二次舔');
},2000);
原文地址:https://www.cnblogs.com/liufeiran/p/11162153.html