Книга: Functional Programming in JavaScript
Назад: Functional reactive programming
Дальше: Putting it all together

Reactivity

Bacon has a function, , that lets us create an event stream, where the event is just a function that is called on the given interval. And the 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 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 library has another trick up its sleeve. The 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 library, we can lazily wait on the eventual values.

Назад: Functional reactive programming
Дальше: Putting it all together

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)