Created
September 10, 2012 13:23
-
-
Save tmdvs/3690878 to your computer and use it in GitHub Desktop.
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
/** | |
* Live updating API JS client side class | |
* @author Tim Davies | |
*/ | |
function liveupdatingClient (container) | |
{ | |
/** | |
* Set up, include handlebars and setup template | |
*/ | |
var endpoint = 'liveupdating.php'; | |
var self = this; | |
var handlebarsInclude = document.createElement('script'); | |
handlebarsInclude.src = 'handlebars.js'; | |
document.getElementsByTagName('head')[0].appendChild(handlebarsInclude); | |
/** | |
* Send a request to the endpoint for additional | |
* data | |
*/ | |
this.request = function(method) | |
{ | |
var result = ""; | |
var request = new XMLHttpRequest(); | |
request.open("POST", endpoint, true); | |
request.setRequestHeader("Content-type","application/x-www-form-urlencoded"); | |
request.send("passkey=098f6bcd4621d373cade4e832627b4f6&method="+method); | |
(function(){(request.readyState == 4)? self.layout(JSON.parse(request.responseText)):setTimeout(arguments.callee,40);})(); | |
} | |
/** | |
* Layout data using handlebars js and template | |
*/ | |
this.layout = function (arr) | |
{ | |
/* Create new row */ | |
var row = document.createElement('div'); | |
row.className = 'liveupdate-row'; | |
/* Compile handlebars source */ | |
var source = "<p>Hello, my name is {{FullName}}</p>"; | |
var template = Handlebars.compile(source); | |
for(map in arr) | |
row.innerHTML += template(arr[map]); | |
document.getElementById(container).appendChild(row); | |
} | |
} | |
/* Let's wait for the page to load */ | |
document.addEventListener('DOMContentLoaded', function () { | |
var api = new liveupdatingClient('live'); | |
api.request('setup'); | |
(function(){api.request('update'); setTimeout(arguments.callee,4000);})(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment