It’s just data

jQuery and Closures

I’ve taken a first look at jQuery, and while I’m generally averse to frameworks, this truly is a library, one that you can use as little or as much as you like, and doesn’t try to do too much.

Its obvious strengths are being CSS selector based and having a consistent approach to collections and chainability.

An example of not trying to do too much is how you enable/disable an element.  That could easily have been encapsulated, but jQuery’s approach seems to be to not sweat the small stuff.

Using jQuery, one quickly picks up a few idioms.  For example, replacing an element typically is done via inserting the replacement before (or after) the current one, and them removing the current one, all in a chain, thus: $("#foo").before(bar).remove().

The net effect of all of this is that you can “write less and do more”, as promised.  But something that more fundamentally changes the way one writes scripts seems to have gone under-reported, at least to my quick scan of the web.  I discovered this trying to make a small mod to an existing data entry application, involving four fields per entry.  This has been used for some time now to create new entries, but now I want to adapt it to handle the updating of existing legacy data which only had three fields.

The approach I selected was to define a button which, when pressed, would cause an “AJAX” request to be issued downloading all of the legacy entries.  Once received, the first input field would be replaced by a dropdown selection box.  Once a selection was made, the selection box would revert back to an input field, three fields would be filled in, a hidden field gets information on the original record to be replaced (in case there is significant editing of the entry) and focus placed on the original fourth and final field.  Nothing fancy, but we have to deal with the fact that everything is asynchronous.

The final code is below:

$("#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;
});

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 are immediately available to the function that is invoked when the selection changes.

With this in place, all that is required is for the server to return a bit of JSON (and all popular languages these days have good libraries for doing so).


Jeremy Zawodny : jQuery and Closures - jQuery and Closures: "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...

Excerpt from HotLinks - Level 1 at

submitted by gst [link] [0 comments]...

Excerpt from javascript: what's new online at

Along different but related lines, I discovered this jQuery event handler idiom a while back. I’ve used it in practically every script I wrote since.

Posted by Aristotle Pagaltzis at

@Sam - Great example. jQuery applications absolutely make high use of closures - but generally to great effect. I’ve been doing my part to try and make sure that more people understand how they work (Recent Advanced JavaScript Talk).

@Aristotle: That is a great pattern - and it could be simplified even more!

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

Note here that the function is being bound anonymously to the change event - but then immediately triggered (creating the same effect as passing a reference to the function in to .each).

Posted by John Resig at

I guess my feeling is that if something is “high use”, discussion of it shouldn’t be buried inside an Advanced JavaScript talk... the topic should be front and certer on this page.

Posted by Sam Ruby at

- $.getJSON('unscanned.cgi', {}, function(unscanned) {
+ $.getJSON($(this).attr('href'), {}, function(unscanned) {

HATEOS FTW!

Posted by Leslie Hensley at

button elements don’t tend to have href attributes...

COD FTW!

Posted by Sam Ruby at

Should be “Its obvious strengths”

Posted by Robert Sayre at

Robert: fixed.  Thanks!

Posted by Sam Ruby at

@Sam - I guess that will teach me to try to be a smart ass in blog comments :)

I write a lot of code like what you describe in this post and have been making an effort to not have any URIs embedded in the JavaScript.  It has seemed to me worth while to decouple my JavaScript from the URI space of my application (site?), but perhaps not considering the tight coupling between the JavaScript and the classes and id on page elements.

I realize this has drifted from the topic of this blog entry, but I would love to see a future post about the intersection of ROA and COD.

Posted by Leslie Hensley at

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...

Excerpt from Ajaxian » Front Page at

Averse. You’re averse to frameworks because (you believe) they have an adverse affect on... not sure.

Posted by Caligula at

Yup.  Fixed.  Thanks!

Posted by Sam Ruby at

I agree with your thoughts on jQuery vs. JS frameworks in general.  It seems to be really unobtrusive to me while at the same time making development easier.  It’s the only JS library that I’ve found pleasurable to work with.

Posted by Scott Johnson at

Ajaxian: 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...

Excerpt from Planet Ajaxian at

There’s a lot of great stuff here - I particularly like the Pagaltzis-Resig technique for firing initial handlers. I’ve been particularly missing this while doing some Flash work recently and realizing just how much further the modern HTML/JavaScript environment has gotten compared to the reams of boiler-plate code you need in the rather similar AS3 environment due to an unfortunate combination of fascist typing and traditional procedural library design.

I wrote something last month which is similarly celebrating how easy it is to enhance the web using jQuery; my focus was on injecting code into a site for which you have limited access (in our case this is a friendly “XSS” for some really squirrelly third-party applications where removing the vendor’s ability to blame bugs on our enhancements was a major consideration) and using Google’s hosting to avoid the need to stash copies of jQuery, jQuery UI, etc. all over the place:

[link]

Posted by Chris Adams at

sirio thinks this is why we all love jQuery

sirio thinks this is why we all love jQuery...

Excerpt from sirio at

Sam Ruby on jQuery

Despite an aversion to frameworks, Sam Ruby is trying out jQuery and generally seems to like what he sees. He says “The net effect of all of this is that you can ‘write less and do more’, as promised.” Tags: jquery javascript...

Excerpt from Phil Windley's Technometria at

Phil Windley - BYU: Sam Ruby on jQuery

Despite an aversion to frameworks, Sam Ruby is trying out jQuery and generally seems to like what he sees. He says “The net effect of all of this is that you can ‘write less and do more’, as promised.”......

Excerpt from Phil Windley's Technometria at

demo: tested on ie, ff, safari, opera, and chrome

Posted by Sam Ruby at

[Web] 連結分享

PHP Five good programming habits in PHP PHP myths confused Working with checkboxes and a database Learning OOP in PHP ASAP! What’s new in PHP V5.3, Part 3: Namespaces Minify - Combine & Compress CSS or Javascript Files The Cost of Test...

Excerpt from 網站製作學習誌 at

[Web] 連結分享

PHP Five good programming habits in PHP PHP myths confused Working with checkboxes and a database Learning OOP in PHP ASAP! What’s new in PHP V5.3, Part 3: Namespaces Minify - Combine & Compress CSS or Javascript Files The Cost of Test...

Excerpt from 網站製作學習誌 at

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...

Excerpt from VJ's Warez at

Add your comment