VJ’s Warez

Ruby on jQuery and Closures

Posted on: January 3, 2009

Sam Ruby has that way about him that sees things very clearly. He just took a peak at jQuery for the first time and was able to really put into words what I think jQuery enthusiasts like about the library:

The notable thing about this is that despite all of the asynchronous events taking place, the code is sequential (nested, but sequential), and that the JSON results of the AJAX call is immediately available to the function that is invoked when the selection changes.

This is based on the following code that he wrote:

  1. $(“#archive”).click(function() {
  2. $.getJSON(‘unscanned.cgi’, {}, function(unscanned) {
  3. // replace realname input field with a selection list
  4. var select = $(‘<select name=”realname” id=”realname”/>’)[0];
  5. for (var i=0; i<unscanned .length; i++) {
  6. select.options[i] = new Option(unscanned[i][1], i);
  7. }
  8. $(‘#realname’).before(select).remove();
  9. $(“#archive”).attr(“disabled”,“disabled”);
  10. // process selection
  11. $(‘#realname’).focus().change(function() {
  12. var icla = unscanned[$(“#realname option:selected”).val()];
  13. $(“#realname”).before(‘<input type=”text” ‘ +
  14. ‘id=”realname” name=”realname”/>’).remove();
  15. $(“#realname”).val(icla[1]);
  16. $(“#pubname”).val(icla[2]);
  17. $(“#email”).val(icla[3]);
  18. $(“#replaces”).val(icla[0] + ‘:’ + icla[3]);
  19. $(“#filename”).val().focus();
  20. $(“#archive”).removeAttr(“disabled”);
  21. });
  22. });
  23. return false;
  24. });

Those that love jQuery, love the API.

John himself had an example in the comments:

  1. $(‘:radio[name=is_user]’)
  2. .change(function(){ $(‘.depends-isuser’)[ this.value == 1 ? ‘show’ : ‘hide’ ](); })
  3. .change();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

VJ’s Warez

%d bloggers like this: