A Pen by Andrew Kirchmyer on CodePen.
Created
November 17, 2013 04:04
-
-
Save akirchmyer/7508990 to your computer and use it in GitHub Desktop.
A Pen by Andrew Kirchmyer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // convenience function | |
| var $ = function(id) { | |
| return document.getElementById(id); | |
| }; | |
| $('vids').onclick = function(e) { | |
| var src, id; | |
| //...... | |
| src = e.target; | |
| if (src.className === "play") { | |
| src.parentNode.innerHTML = videos.getPlayer(id); | |
| return; | |
| } | |
| //...... | |
| // get the info on the selected video | |
| videos.getInfo(id); | |
| }; | |
| var videos = { | |
| getPlayer: function(id) {}, | |
| updateList: function(data) {}, | |
| getInfo: function(id) { | |
| var info = $('info' + id); | |
| if (!info) { | |
| // make the http request if we have no info on the selected video | |
| proxy.makeRequest([id], "videos.updateList"); | |
| return; | |
| } | |
| //......... | |
| } | |
| } | |
| var proxy = { | |
| ids: [], | |
| delay: 50, | |
| timeout: null, | |
| callback: null, | |
| context: null, | |
| makeRequest: function(id, cb, context) { | |
| this.ids.push(id); | |
| this.cb = cb; | |
| this.context = context; | |
| if(!this.timeout){ | |
| this.timeout = setTimeout(function() { | |
| proxy.flush(); | |
| }, this.delay); | |
| } | |
| }, | |
| flush: function() { | |
| // make the http request for each of the ids | |
| http.makeRequest(this.ids, 'proxy.handler'); | |
| //clear timeout and queue | |
| this.timeout = null; | |
| this.ids = []; | |
| }, | |
| handler: function(data) { | |
| var i, max; | |
| // single video | |
| if (data.query.count === 1) { | |
| proxy.cb.call(proxy.context, data.query.results.Video); | |
| return; | |
| } | |
| // multiple videos | |
| for (i=0, max = data.query.results.Video.length; i< max; i+=1){ | |
| proxy.cb.call(proxy.context, data.query.results.Video[i]); | |
| } | |
| } | |
| }; | |
| var http = { | |
| makeRequest: function(ids, cb) { | |
| var url = "http://videos.com/api?ids=" + ids + 'handler=' + cb, | |
| script = document.createElement('script'); | |
| script.src = url; | |
| document.body.appendChild(script); | |
| } | |
| } | |
| // I excluded lots of validation and other stuff from the examples for the sake of brevity. | |
| //This is very much incomplete, it just demonstrates an event handler making http requests through a proxy, rather than making the requests directly. | |
| //This can greatly improve performance by bundling all requests for content into one request |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment