jquery 

continuous data stream






GPL/MIT/Copyleft - @molokoloco 2012 - http://b2bweb.fr

PrOblem


1) I want a continuous animation
2) Data came from asynchronous ajax call


For example...
Imagine an animation that need a new tweet
each 10 seconds, indefinitely

Data emitter


I need to create a function that will give a new tweet each time we call it...

> At the first call, ajax will be pending, so nothing to give back ?


jQuery : The Deferred object

jQuery.Deferred()

"Introduced in version 1.5,
is a chainable utility object 
that can register multiple callbacks 
into callback queues, invoke callback queues, 
and relay the success or failure state
of any synchronous or asynchronous function."

http://api.jquery.com/category/deferred-object/

DEMOS


Ok let's go with our data EMITTER...
jQuery.boxFx test case : Stream Twitter w/ JSONP

- Simple : http://jsfiddle.net/molokoloco/Ebc27/
- Full : http://jsfiddle.net/molokoloco/sBqWq/

(More infos ?)
https://github.com/molokoloco/jQuery.boxFx

Give back a promise !

"I will do the job ! yes sir"

Each call to the data function will give back a "promise"
return dfd.promise(); // Give back the promise to do the job

The "animate" function will have to  take care
of the asynchronous data...
$.when(options.dataStream($this))
 .done(function($this_, data) { /* OK... animate !!! */ });


The trick is not to forgot your context... : "this"

Resolve your data


When result became available, data function
will give it back...


for (var i in reqQueue) { // Resolve awaiting result(s)
reqQueue[i]['dfd'].resolve(reqQueue[i]['context'], twitsObj[i]);
}
>>> have to resolve all "promise"... ! Tricky ?
Dequeuing pending requests with associates contexts

The good part


It was a little pain to write the template..
But now, with this code : 

1) It's very easy to change, extend, the data provider function
2) The animation is completly agnostic to data api (unless you ask for 5000 tweets in 200ms)

ANY questions ?









Thanks !
Made with Slides.com