Skip to content

Instantly share code, notes, and snippets.

@forforf
Created November 27, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forforf/4154617 to your computer and use it in GitHub Desktop.
Save forforf/4154617 to your computer and use it in GitHub Desktop.
Using jQuery Deferred Promises with Arrays
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"
<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