Monday, October 13th, 2008
Ruby on jQuery and Closures
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:
-
-
$("#archive").click(function() {
-
$.getJSON('unscanned.cgi', {}, function(unscanned) {
-
-
// replace realname input field with a selection list
-
var select = $('<select name="realname" id="realname"/>')[0];
-
for (var i=0; i<unscanned .length; i++) {
-
select.options[i] = new Option(unscanned[i][1], i);
-
}
-
$('#realname').before(select).remove();
-
-
$("#archive").attr("disabled","disabled");
-
-
// process selection
-
$('#realname').focus().change(function() {
-
var icla = unscanned[$("#realname option:selected").val()];
-
$("#realname").before('<input type="text" ' +
-
'id="realname" name="realname"/>').remove();
-
$("#realname").val(icla[1]);
-
$("#pubname").val(icla[2]);
-
$("#email").val(icla[3]);
-
$("#replaces").val(icla[0] + ':' + icla[3]);
-
$("#filename").val('').focus();
-
$("#archive").removeAttr("disabled");
-
});
-
});
-
return false;
-
});
-
Those that love jQuery, love the API.
John himself had an example in the comments:
-
-
$(':radio[name=is_user]')
-
.change(function(){ $('.depends-isuser')[ this.value == 1 ? ‘show’ : ‘hide’ ](); })
-
.change();
-












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,