Monday, October 13th, 2008

Ruby on jQuery and Closures

Category: jQuery, JSON

<p>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:

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

Those that love jQuery, love the API.

John himself had an example in the comments:

javascript
< view plain text >
  1. $(':radio[name=is_user]')
  2.   .change(function(){ $('.depends-isuser')[ this.value == 1 ? ‘show’ : ‘hide’ ](); })
  3.   .change();

Posted by Dion Almaer at 6:40 am
1 Comment

++---
2.3 rating from 32 votes

1 Comment »

Comments feed TrackBack URI

have to admit although most of my work is in Prototype & Scriptaculous, jQuery is one of those things i love.

It’s so compact and fast, if you’re not after something big and weighty, you can build some excellent stuff in it (have replaced my rails blog with jquery for the small footprint alone).

Great stuff,

Comment by indiehead — October 13, 2008

Leave a comment

You must be logged in to post a comment.