/** Example: * event.create ("Namespace1"). Listen (' click ', Function (a) {* Console.log (a); *}); * Event.create ("Namespac E1 "). Trigger (" click ", 1); */window.myevent= (function() { varGlobal = This, Event, _default= ' Default '; Event=function() { var_listen, _trigger, _remove, _slice=Array.prototype.slice, _shift=Array.prototype.shift, _unshift=Array.prototype.unshift, Namespacecache=[], _create, find, each=function(ary, fn) {varret; for(vari = 0, L = ary.length; I < L; i++) { varn =Ary[i]; RET=Fn.call (n, I, n); } returnret; }; //Subscribe_listen =function(Key, FN, cache) {if(!Cache[key]) {Cache[key]= []; } cache[key].push (FN); }; //To remove a subscription_remove =function(key, Cache, fn) {if(Cache[key]) {if(FN) { for(vari = cache[key].length; I >=0; i++) { if(Cache[key][i] = = =fn) {Cache[key].splice (i,1); } } }Else{Cache[key]= []; } } }; //Publish_trigger =function() { varCache =_shift.call (arguments), key=_shift.call (arguments), args=arguments, _self= This, ret, Stack=Cache[key]; if(!stack | |!stack.length) {return; } returnEach (Stack,function() { return This. Apply (_self, args); }); }; //Create a namespace_create =function(namespace) {varNamespace = Namespace | |_default; varCache ={}, Offlinestack= [],//Offline EventsRET ={listen:function(Key, FN, last) {_listen (key, FN, cache); if(Offlinestack = =NULL) { return; } if(last = = = ' last ')) {Offlinestack.length&&Offlinestack.pop () (); } Else{each (Offlinestack,function () { This(); }); } offlinestack=NULL; }, one:function(Key, FN, last) {_remove (key, cache); This. Listen (key, FN, last); }, remove:function(Key, FN, last) {_remove (key, Cache, FN); }, Trigger:function() { varFN, args, _self= This; _unshift.call (arguments, cache); Args=arguments; FN=function() { return_trigger.apply (_self, args); }; if(offlinestack) {returnOfflinestack.push (FN); } returnfn (); } }; returnNamespace? (Namespacecache[namespace]? Namespacecache[namespace]: namespacecache[namespace] =ret): ret; }; return{create: _create, one:function(Key, FN, last) {varevent = This. Create (); Event.one (Key, FN, last); }, remove:function(Key, FN) {varevent = This. Create (); Event.remove (key, FN); }, listen:function(Key, FN, last) {varevent = This. Create (); Event.listen (Key, FN, last); }, Trigger:function() { varevent = This. Create (); Event.trigger.apply ( This, arguments); } }; }(); returnEvent;}) ();
JS Custom Event Watcher Mode (Publish/subscribe)