EventContainer:发布-订阅公共组件
//发布-订阅组件 function EventContainer(){ var _events={}; this.subscribe=function(event,func){ if(Object.prototype.toString.apply(_events[event])!=="[object Array]"){ _events[event]=[]; } _events[event].push(func); }; this.trigger=function(event){ var handlers = _events[event]; if(Object.prototype.toString.apply(handlers)==="[object Array]"){ for (var i = 0,len=handlers.length; i <len; i++) { handlers[i](); } } }; }
ShopcartBusiness:购物车页面逻辑
function ShopCartBusiness(){ if (window.eventContainer===undefined) { window.eventContainer=new EventContainer(); } window.eventContainer.subscribe("login",function(){ alert("login success!"); }); window.eventContainer.subscribe("login",function(){ alert("login success2!"); }); window.eventContainer.subscribe("regist",function(){ alert("regist success!"); }); //打开登录弹窗 var loginBox = new LoginBox(); } var shopCart = new ShopCartBusiness();
LoginBox:弹窗逻辑
function LoginBox(){ if (window.eventContainer===undefined) { window.eventContainer=new EventContainer(); } var _initEvents=function(){ $("#btnLogin").on("click",function(){ window.eventContainer.trigger("login"); }); $("#btnRegist").on("click",function(){ window.eventContainer.trigger("regist"); }); }; _initEvents(); }
原文:https://www.cnblogs.com/fanfan-90/p/12781680.html