1 <script type="text/javascript"> 2 //挂插着模式又叫发布订阅模式应该是最常用的模式 3 4 //1,dom事件就是观察者模式,只要订阅了click事件,当点击div的时候,function click就会触发。 5 div.onclick=function click() { 6 alert("click"); 7 } 8 9 //2 10 loadImage(imgAry,function(){ 11 Map.init(); 12 Gamer.init(); 13 }); 14 loadImage(imgAry,function(){ 15 Map.init(); 16 Gamer.init(); 17 Sound.Init(); 18 }); 19 20 loadImage.listen("ready",function(){ 21 Map.init(); 22 }); 23 loadImage.listen("ready",function(){ 24 Gamer.init(); 25 }); 26 loadImage.listen("ready",function(){ 27 Sound.init(); 28 }); 29 //3, 30 Events=function(){ 31 var listen,log,obj,one,remove,trigger,__this; 32 obj={}; 33 __this=this; 34 listen=function(key,eventfn){ 35 var stack,_ref; 36 stack=(_ref=obj[key])!=null?_ref:obj[key]=[]; 37 return stack.push(eventfn); 38 }; 39 one=function(key,eventfn){ 40 remove(key); 41 return listen(key,eventfn); 42 }; 43 remove=function(key){ 44 var _ref; 45 return (_ref==obj[key])!=null?_ref.length=0:void 0; 46 }; 47 trigger=function(){ 48 var fn,stack,_i,_len,_ref,key; 49 key=Array.prototype.shift.call(arguments); 50 stack=(_ref=obj[key])!=null?_ref:obj[key]=[]; 51 for(_i=0,_len=stack.length;_i<_len;_i++){ 52 return false; 53 } 54 }; 55 return{ 56 listen:listen, 57 one:one, 58 remove:remove, 59 trigger:trigger 60 }; 61 }; 62 63 var adultTV=Events(); 64 adultTV.listen("play",function(data){ 65 alert("今天XXXXX"+data.name); 66 }); 67 adultTV.trigger("play",{"name":"XX"}); 68 </script>