码迷,mamicode.com
首页 > 其他好文 > 详细

发布订阅

时间:2019-07-10 11:03:14      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:发布   参数   apply   foreach   理想   event   OLE   this   log   

 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));//在其他地方叫展开运算符
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>

 

发布订阅

标签:发布   参数   apply   foreach   理想   event   OLE   this   log   

原文地址:https://www.cnblogs.com/liufeiran/p/11162153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!