Created
November 27, 2012 14:50
-
-
Save forforf/4154617 to your computer and use it in GitHub Desktop.
Using jQuery Deferred Promises with Arrays
This file contains 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
makeButton = (id) -> | |
$("<button id=\"button#{id}\">Button #{id}</button>") | |
$ -> | |
$('#go').click (evt)-> | |
$('#buttons').empty() | |
$("#messages").empty() | |
qty = parseInt $('#qty').val() | |
qty = 1 if qty < 1 | |
buttons = (makeButton(i) for i in [0..qty-1]) | |
$('#buttons').append($(button)) for button in buttons | |
messages = $("#messages") | |
messages.appendText = (message) -> @append "<li>#{message}</li>" | |
buttons_dfds = (new $.Deferred for button in buttons) | |
buttons_promises = (dfd.promise() for dfd in buttons_dfds) | |
dfd_idxs = [0..buttons_dfds.length-1] | |
buttons_resolve = (buttons[i].click buttons_dfds[i].resolve for i in dfd_idxs) | |
$.when.apply($, buttons_promises).then () => | |
messages.appendText "All buttons clicked" |
This file contains 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://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> | |
<script type="text/javascript" src="test.js"></script> | |
<link rel="stylesheet" href="test.css"></link> | |
</head> | |
<body> | |
<div id="messages"></div> | |
<div> | |
<input id="qty" type="text" name="qtyn" /> | |
<button id="go">Go</button> | |
</div> | |
<div id="buttons"> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment