Bacon has a function, Bacon.fromPoll()
, that lets us create an event stream, where the event is just a function that is called on the given interval. And the stream.subscribe()
function lets us subscribe a handler function to the stream. Because it's lazy, the stream will not actually do anything without a subscriber.
var eventStream = Bacon.fromPoll(10000, function(){ return Bacon.Next; }); var subscriber = eventStream.subscribe(function(){ var url = 'http://api.server.com/election-data?format=json'; var data = jQuery.ajax(url); var newRegions = getRegions(data); container.innerHTML = newRegions.map(function(r){ return r.render(); }).join(''); });
By essentially putting it in a loop that runs every 10 seconds, we could get the job done. But this method would hammer-ping the network and is incredibly inefficient. That would not be very functional. Instead, let's dig a little deeper into the Bacon.js
library.
In Bacon, there are EventStreams and Properties parameters. Properties can be thought of as "magic" variables that change over time in response to events. They're not really magic because they still rely on a stream of events. The Property changes over time in relation to its EventStream.
The Bacon.js
library has another trick up its sleeve. The Bacon.fromPromise()
function is a way to emit events into a stream by using promises. And as of jQuery version 1.5.0, jQuery AJAX implements the promises interface. So all we need to do is write an AJAX search function that emits events when the asynchronous call is complete. Every time the promise is resolved, it calls the EvenStream's subscribers.
var url = 'http://api.server.com/election-data?format=json'; var eventStream = Bacon.fromPromise(jQuery.ajax(url)); var subscriber = eventStream.onValue(function(data){ newRegions = getRegions(data); container.innerHTML = newRegions.map(function(r){ return r.render(); }).join(''); }
A promise can be thought of as an eventual value; with the Bacon.js
library, we can lazily wait on the eventual values.