Javascript 发布订阅组件
公共的发布订阅组件,不需要再在组件中写发布订阅相关逻辑,用于模块间解耦,支持排序、传参,原创~
EventContainer:发布-订阅公共组件
Array.prototype.sort = function (fn) {//数组排序 var temp; fn = fn || function (a, b) { return a > b; }; for (var i = 0, len = this.length; i < len; i++) { for (var j = i + 1; j < len; j++) { if (fn(this[i], this[j])) { temp = this[i]; this[i] = this[j]; this[j] = temp; } } } return this; }; function EventContainer(){ var _events={}; var _getType=Object.prototype.toString; /* 两种订阅方式,1、通过函数;2、通过对象 */ this.subscribe=function(event,arg){/*arg is Function or Object*/ var func,sort=0; if(_getType.apply(arg)==="[object Object]"){ func = arg.func; sort = arg.sort; } else if(_getType.apply(arg)==="[object Function]"){ func = arg; } else{ return; } if(_getType.apply(_events[event])!=="[object Array]"){ _events[event]=[]; } _events[event].push({func:func,sort:sort}); }; this.trigger=function(event,data){ var handlers = _events[event]; if(_getType.apply(handlers)==="[object Array]"){ handlers = handlers.sort(function(a,b){return a.sort>b.sort}); for (var i = 0,len=handlers.length; i <len; i++) { handlers[i]["func"](data); } } }; }
ShopcartBusiness:购物车页面逻辑,在此模块中订阅事件
//购物车页面逻辑-shopcart.js function ShopCartBusiness(){ if (window.eventContainer===undefined) { window.eventContainer=new EventContainer(); } /* 两种订阅方式,1、通过函数;2、通过对象 */ window.eventContainer.subscribe("login",function(data){ console.info("login success!"); console.info(data); }); window.eventContainer.subscribe("login",{"sort":3,"func":function(data){ console.info("login success3!"); console.info(data); } }); window.eventContainer.subscribe("login",{"sort":5,"func":function(data){ console.info("login success5!"); console.info(data); } }); window.eventContainer.subscribe("login",{"sort":2,"func":function(data){ console.info("login success2!"); console.info(data); } }); window.eventContainer.subscribe("login",{"sort":1,"func":function(data){ console.info("login success1!"); console.info(data); } }); window.eventContainer.subscribe("regist",function(data){ console.info("regist success!"); console.info(data); }); //打开登录弹窗 var loginBox = new LoginBox(); }
LoginBox:弹窗逻辑,在此模块中发布消息
function LoginBox(){ if (window.eventContainer===undefined) { window.eventContainer=new EventContainer(); } var _initEvents=function(){ $("#btnLogin").on("click",function(){ window.eventContainer.trigger("login","参数11"); }); $("#btnRegist").on("click",function(){ window.eventContainer.trigger("regist","参数22"); }); }; _initEvents(); }