Skip to content

Instantly share code, notes, and snippets.

@toolness
Last active August 29, 2015 14:05
Show Gist options
  • Save toolness/5ca4bb166c06f24218ad to your computer and use it in GitHub Desktop.
Save toolness/5ca4bb166c06f24218ad to your computer and use it in GitHub Desktop.
An attempt to implement infinite scrolling using Bacon.js, a Functional Reactive Programming (FRP) library.
<!DOCTYPE html>
<meta charset="utf-8">
<title>Bacon.js Infinite Scroll Attempt #2</title>
<p>Keep scrolling down to see more numbers.</p>
<div id="results"></div>
<img id="throbber" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Ajax-loader.gif" style="position: fixed; bottom: 4px; right: 4px;">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bacon.js/0.7.22/Bacon.js"></script>
<script>
var pageChanged = new Bacon.Bus();
var showMore = pageChanged.filter(function() {
var bottom = $('#results').offset().top + $('#results').height();
return bottom - window.pageYOffset < window.innerHeight;
});
var results = showMore.flatMapFirst(function() {
return Bacon.fromCallback(function getMoreNumbers(cb) {
// We're just faking an Ajax request here.
setTimeout(function() { cb([1, 2, 3, 4, 5].map(Math.random)); }, 1000);
});
});
showMore.awaiting(results).onValue($('#throbber'), 'toggle');
results.onValue(function(results) {
results.forEach(function(result) {
$('<h2></h2>').text(result.toFixed(3)).appendTo('#results');
});
});
pageChanged.plug(Bacon.mergeAll(
$(window).asEventStream('resize'),
$(window).asEventStream('scroll'),
results.delay(10),
Bacon.once()
));
</script>
@SimplGy
Copy link

SimplGy commented May 1, 2015

I got interested in FRP too, and infinite scroll seemed like a really great candidate. I did a solution that pays a lot of attention to how the UI streams impact the visible range: https://gist.github.com/SimplGy/d6362369ac4ebf27f3ec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment