Now that we have the reactivity covered, we can finally play with some code.
We can modify the subscriber with chains of pure functions to do things such as adding up a total and filtering out unwanted results, and we do it all within onclick()
handler functions for buttons that we create.
// create the eventStream out side of the functions var eventStream = Bacon.onPromise(jQuery.ajax(url)); var subscribe = null; var url = 'http://api.server.com/election-data?format=json'; // our un-modified subscriber $('button#showAll').click(function() { var subscriber = eventStream.onValue(function(data) { var newRegions = getRegions(data).map(function(r) { return new Region(r.name, r.percent, r.parties); }); container.innerHTML = newRegions.map(function(r) { return r.render(); }).join(''); }); }); // a button for showing the total votes $('button#showTotal').click(function() { var subscriber = eventStream.onValue(function(data) { var emptyRegion = new Region('empty', 0, [{ name: 'Republican', votes: 0 }, { name: 'Democrat', votes: 0 }]); var totalRegions = getRegions(data).reduce(function(r1, r2) { newParties = r1.parties.map(function(x, i) { return { name: r1.parties[i].name, votes: r1.parties[i].votes + r2.parties[i].votes }; }); newRegion = new Region('Total', (r1.percent + r2.percent) / 2, newParties); return newRegion; }, emptyRegion); container.innerHTML = totalRegions.render(); }); }); // a button for only displaying regions that are reporting > 50% $('button#showMostlyReported').click(function() { var subscriber = eventStream.onValue(function(data) { var newRegions = getRegions(data).map(function(r) { if (r.percent > 50) return r; else return null; }).filter(function(r) {return r != null;}); container.innerHTML = newRegions.map(function(r) { return r.render(); }).join(''); }); });
The beauty of this is that, when users click between the buttons, the event stream doesn't change but the subscriber does, which makes it all work smoothly.