Posts Tagged ‘jQuery’

Moving to jQuery from RJS: Getting Started

Props to this guy’s post.

Some parts are kind of confusing, but it’s a testatment to how much code he posts that I didn’t even realize he was French until I sat down to write this post and read it more carefully — he communicated mostly in code.

He gives a good Rails application.js file for you to start out with — basically it provides a bunch of handles for things you want to remote w/ XHR. They use the new-ish jQuery method unbind to make sure that regular events on items designated as AJAX get overriden. Pretty slick and a good way to think of jQuery’s usage in an app context. So far, I hadn’t really used it for AJAX beyond a thing I wrote to enable cross-domain MX record validation.

Example: remote links

Rails provides the link_to_remote helper to let you create links that will trigger a GET over XHR. This application.js defines a jQuery function for that and then binds it to a certain class of links — “get”:

1
2
3
4
5
6
7
8
jQuery.fn.getWithAjax = function() {
    this.unbind('click', false);
    this.click(function() {
      $.get($(this).attr("href"), $(this).serialize(), null, "script");
      return false;
    })
    return this;
  };

Which is then set with this:

1
$('a.get').getWithAjax();

Now any anchor with class “get” on it will result in a remote call to the URL in that anchor’s href. Combined with a respond_to block in your controller to handle Javascript and a Javascript template file, you can use links like this to (for instance) load ActiveRecord objects into a page using AJAX. Instead of “show.erb.html” your controller’s show method is handled by “show.js.erb”. This block in the show method of the controller ensures that it is activated correctly:

1
2
3
4
respond_to do |format|
  format.html
  format.js { render :layout => false }
end

Because the call came in over XHR, the controller sees the format as being JS and responds with the instructions set in the block passed to format.js. Rendering without layout ensures that nothing but the rendered data plus the template is returned.

Notice that the AJAX call in the above snippet from application.js uses the “script” datatype. This specifies that the returned data should be evaluated as Javascript, which is what we want, because the returned data includes the jQuery-based instructions we have inside show.js.erb, and those need to get evaluated (not just displayed) in order for the page to look right.

An aside: One thing that this makes me think about a lot is how important visual design is when you’re developing an application. Your design has to correspond concretely to a DOM with all sorts of manipulative handles (ids and classes) and all sorts of custom functions built to do various things to/with them. You’d damn well better draw a decent picture of this and give the elements of it some good names that make sense. In fact, I think a lot of the true work in programming involves drawing pictures (I still model some embarrassingly simple relationships with pencil and paper), but that might just be the way that my brain works.

Anywho, I took the above application.js and used it as the basis for a conversion from RJS to jQuery in a Rails app I’m working on. I’ll probably end up adding quite a bit to his stuff as I go, but having this file around made starting the transition process a lot easier.

I expect to do some more posts on the conversion as I go, since I haven’t found a whole lot of stuff yet that’s oriented toward “strategies for using jQuery with Rails” and wasn’t written in 2007. RJS kept me from dealing w/ JS directly as a major component of my app, but those days are over now that I’m committed to unobtrusive JS via jQuery, and a more thought-out approach will be necessary.

Loving JQuery

As someone involved with a decent amount of Rails programming over the past year, most of my work in Javascript frameworks has centered on Prototype and script.aculo.us. And with good reason — both are enormously capable and, with Prototype at least, extremely well documented. They create beautiful effects and nearly painless AJAX, they integrate really well with Rails, and there’s a wide community of users you can slot yourself right into. I’ve used some other frameworks as well — made interfaces with ExtJS and messed around with MochiKit some — and I’ve discovered that every one of these things (with the possible exception of MochiKit, which seems to be essentially abandonware at this point) has a specific niche to fill.

But for the most part, what all these things have in common is that they seem to have been created with web application interface development in mind. They’re not all that well suited to the set of one-off needs that crop up with general forms and lead generation tools on your average small site, but a lot of people end up using them for that anyway because they remove some of the tedium from JS. Numerous blog posts have been written about the phenomenon of people including the entirety of Prototype just to make tiny, “DHTML” DOM manipulation a little less painful, which makes no sense. Just suck it up and use JS for real. It’s not that hard.

There are some tasks that fall in between though — they’re more than trivial with bare JavaScript, but loading the entirety of a framework like Prototype is kind of like using a chainsaw to trim hedges. It’ll work, but it will be heavy and imprecise, and you may find yourself regretting all the extra work later. You still need a tool though, so what’s the solution?

A smaller, more task-oriented framework. This week, I decided that I’m a fan of JQuery. Here are the two examples from this work week that sold me:

Cycle

The Cycle plugin makes it dead simple to create a slideshow effect.

It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and many transition effects including fade, shuffle, scroll, turn and zoom. It also allows you to define and run your own custom transitions. In addition, it supports, but does not require, the Metadata Plugin and the Easing Plugin.

The basic way it works is that you put together a div filled with the objects you want to cycle, usually other divs containing, say, an image and a caption. Once you’ve got your structure set up, you call cycle with one line, which it’s good to place at the bottom of your HTML so you’ll know all your pictures have loaded:

1<tt>
</tt>2<tt>
</tt>3<tt>
</tt>
  <span class="ta">&lt;script</span> <span class="an">type</span>=<span class="s"><span class="dl">&quot;</span><span class="k">text/javascript</span><span class="dl">&quot;</span></span> <span class="an">charset</span>=<span class="s"><span class="dl">&quot;</span><span class="k">utf-8</span><span class="dl">&quot;</span></span><span class="ta">&gt;</span><tt>
</tt>    $('#mydiv').cycle();<tt>
</tt>  <span class="ta">&lt;/script&gt;</span><tt>
</tt>

You can add all kinds of options in the call to cycle, but the bare effect itself is pretty pleasing and is frequently exactly what a developer is looking for.

UI.Datepicker

UI.Datepicker is part of the JQuery UI library. You can think of UI as being script.aculo.us to JQuery’s Prototype — it’s built on top of the JQuery core and provides visual effects like fade, appear/disappear, window shade, shrink, grow, etc. It also contains all the drag/drop-oriented stuff you might need, as well as several other “widgets” and interaction pieces.

Datepicker is a widget that provides a calendar. When a user clicks on a form text field which has been tied to a Datepicker object, a calendar appears. The user navigates the calendar and chooses a date, which is then inserted into the text field. Again, the implementation code is short:

You could one-line this at the bottom of your page as well if you wanted (as with cycle above), but using JQuery’s $(document).ready() enables you to ensure that the code won’t try to execute before the page is loaded, so you can keep code you might use a bunch (like a standard calendar widget) outside your HTML file in a central spot.

1<tt>
</tt>2<tt>
</tt>3<tt>
</tt>4<tt>
</tt><strong>5</strong><tt>
</tt>
  <span class="ta">&lt;script</span> <span class="an">type</span>=<span class="s"><span class="dl">&quot;</span><span class="k">text/javascript</span><span class="dl">&quot;</span></span> <span class="an">charset</span>=<span class="s"><span class="dl">&quot;</span><span class="k">utf-8</span><span class="dl">&quot;</span></span><span class="ta">&gt;</span><tt>
</tt>   $(document).ready(function(){<tt>
</tt>     $('#date').datepicker({dateFormat:'yy-mm-dd'});<tt>
</tt>   });<tt>
</tt>  <span class="ta">&lt;/script&gt;</span><tt>
</tt>

One thing I love about the JQuery UI site: you get to build your own download — i.e., you can select the pieces of code you need by feature and have the file built with just that code. Among JavaScript frameworks, I believe this may be unique to JQuery, and it makes a serious difference in the file size.

I believe that this attitude — favoring modular code, giving you only what you need so you don’t end up with page bloat — probably drives a lot of JQuery’s adoption in smaller-need situations like the ones I’m describing here. But JQuery is also the native JS framework for both Drupal and WordPress. I haven’t messed with MooTools or Dojo yet, but I think of them as being in a similar class to JQuery, and I think JQuery definitely has the momentum to draw in more converts the same way I was: dead-simple use, only-what-you-need philosophy of code distribution, pervasive understanding of the bandwidth challengers front-end web developers face.

Tags: ,