Created
April 16, 2014 01:01
-
-
Save dmcclory/10794564 to your computer and use it in GitHub Desktop.
Bacon.js example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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