JavaScript设计模式之代理模式

代理模式

代理模式合并多个复杂业务请求,减轻web服务器压力

页面框架

'toggle-all'>Toggle Checked

  1. "checkbox" checked> "http://new.music.yahoo.com/videos/--2158073">
  2. "checkbox" checked> "http://new.music.yahoo.com/videos/--2158073">
  3. "checkbox" checked> "http://new.music.yahoo.com/videos/--2158073">
  4. "checkbox" checked> "http://new.music.yahoo.com/videos/--2158073">
  5. "checkbox" checked> "http://new.music.yahoo.com/videos/--2158073">
//事件处理函数 $ = document.getElementById; $('vids').onclick = function (e) { Var id,src; e = e || windows.event; Src = e.target || e.srcElement; if(src.nodeName !== 'A'){ return; } if(typeof e.preventDefault === 'function'){ e.preventDefault(); } e.returnValue = false; id = src.href.split('--')[1]; if(src..className === 'play'){ src.parentNode.innerHtml = videos.getPlayer(id); return; } src.parentNode.id = 'v' + id; videos.getInfo(id); } $('toggle-all').onclick = function (e) { var I,hrefs,max,id; hrefs = $('vids').getElementByTagName('a'); max = hrefs.length; for(I = 0;i < max;I++){ if(hrefs[I].className === 'play'){ continue; } if(hrefs[I].parentNode.firstChild.checked){ continue; } id = hrefs[I].href.split('--')[1]; hrefs[I].parentNode.id = 'v' + id; videos.getInfo(id); } } //videos对象 Videos = { getPlayer: function (id){...}, updateList: function (data){...}, getInfo: function (id){ var info = $('info' + id); if(!info){ proxy.makeRequest(id,this.updateList,vedios); return; } if(info.style.display === 'none'){ info.style.display = ''; }else{ info.style.display = 'none'; } } }; //http对象 //添加一个脚本,脚本内容为产生JSONP格式的请求到Yahoo!的YQL Web服务器 //sql未YQL查询语言(该语言类似sql语言) Var http = { makeRequest: function (ids,callback) { var url = 'http://query.yahooapis.com/v1/public/yql?q=', format = 'select * from music.video.id where ids IN (%ID%)', handler = 'callback=' + callback, script = document.createElement('script'); sql = sql.replace('%ID%',ids.join('","')); sql = encodeURIComponent(sql); document.body.appendChild(script); } }; //现在加入proxy代理对象,videos对象会先调用proxy,然后proxy50ms的缓存队列之后会集中处理http请求,访问http对象 Proxy = { ids: [], delay: 50,//缓存队列的缓存时间 timeout: null, callback: null, context: null, makeRequest: function (id,callback,context){ this.ids.push(id); this.callback = callback; this,context = context; //设置超时时间 if(timeout){ setTimeout(function () { proxy.flush(); },this.delay); } }, flush: function () { http.makeRequest(ids,'proxy.callback'); //清除缓冲队列 this.timeout = null; this.ids = []; }, handler: function (data) { //不同于videos的updateList回调,handler可以处理多个数据,适用于缓冲队列的多个http请求数据处理 var I,max; if(parseInt(data.query.count,10) === 1){ //单个视频 proxy.callback.call(this.context,data.query.result.Video); return; } for(I = 0, max = data.query.result.Video.length;;I < max;i++){ //多个视频 proxy.callback.call(this.context,data.query.result.Video[i]); } } };

你可能感兴趣的:(前端技术,js)