Streaming asynchronous result to a function call
by molokoloco
CSS
div {
min-height:50px;
margin:10px;
padding:5px;
border-radius:5px;
background:orange;
overflow:hidden;
font:11px trebuchet,verdana;
color:darkblue;
}
img {
float:right;
border:1px solid darkblue;
width:48px;
height:48px;
}
JavaScript
// http://stackoverflow.com/questions/8190016/jquery-function-to-give-a-result-at-each-call-but-with-asynchronous-jsonp-insid
// Pb : i want to pass a function ("streamNewTweet") to a plugin
// and each call (delayed or not) to this function have to give back a new result (one tweet for exemple)
// BUT, data came from JSONP asynchronous callback...
$(document).ready(function() {
// Debug..
var db = function() {
'console' in window && console.log.call(console, arguments);
};
////////////////////////////////////////////////////////////////////////////////////////
// I want each call to "streamNewTweet()" to give back a new tweet...
var twitsObj = null,
current = 0,
jsonReq = null,
reqQueue = [];
var streamNewTweet = function(_context) {
var dfd = $.Deferred(); // http://api.jquery.com/category/deferred-object/
if (!jsonReq) { // Let's do our first request
console.log('Call service');
jsonReq = $.ajax({
cache: false,
dataType: 'jsonp',
url: 'http://search.twitter.com/search.json',
data: {q: 'html5'},
success: function(data) {
console.log('Service result');
twitsObj = $.map(data.results, function(obj) { // Create obj with all tweets
return {
username: obj.from_user,
tweet: obj.text,
avatar: obj.profile_image_url
};
});
for (var i in reqQueue) { // Resolve awaiting result(s)
if (i in twitsObj) reqQueue[i]['dfd'].resolve(reqQueue[i]['context'], twitsObj[i]);
else { // trop de demande en attentes ? > reload
reqQueue = reqQueue.slice(i);
return;
...