Skip to content

Instantly share code, notes, and snippets.

@dmcclory
Created April 16, 2014 01:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmcclory/10794564 to your computer and use it in GitHub Desktop.
Save dmcclory/10794564 to your computer and use it in GitHub Desktop.
Bacon.js example
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/bacon.js/0.7.10/bacon.js"></script>
</head>
<body>
<div>Running total: <span id="amount"></span></div>
<div id="ledger">
<input type="text" id="entry">
<button>Awesome!</button>
</div>
<script>
var clicks = $('#ledger button').asEventStream('click')
var keyPresses = $(document).asEventStream('keypress')
// look at these two lines!
var enters = keyPresses.filter( function(k) { return k.keyCode == 13 } )
var values = Bacon.mergeAll([clicks, enters]).map( function(f) { return Number( $('#ledger input').val()) })
// total is a property - stream that receives events
// but also has state.
var total = values.scan(0, function(m, n) { return m + n } )
total.onValue( function(v) { $('#amount').html(v) } )
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment