Yehuda Katz is a member of the Ember.js, Ruby on Rails and jQuery Core Teams; he spends his daytime hours at the startup he founded, Tilde Inc.. Yehuda is co-author of best-selling jQuery in Action and Rails 3 in Action. He spends most of his time hacking on open source—his main projects, like Thor, Handlebars and Janus—or traveling the world doing evangelism work. He can be found on Twitter as @wycats and on Github.

Archive for the ‘jQuery’ Category

Call For Papers

Those of you who have been around for a while know that in September of last year I published the first issue of the Visual jQuery Magazine. In October, the magazine was also released in French.

The mag had interviews with important jQuery community members (like creator John Resig, plugin editor Dave Cardwell, etc.), articles on jQuery features and implementations, and even a piece or two on alternate Javascript libraries, complete with quality graphics and original art.

The positive response was incredible, and people really seemed to like it. Unfortunately, though I’d initially planned on making the magazine a monthly publication, things fell to the wayside as my schedule got progressively more hectic. Since Issue 1 I’ve found a new job (new then; about eight or nine months old now), moved across the country (NY to CA), and gotten a huge chunk of the way through writing my first book (stay tuned for details!). Clearly, things have been busy.

The lack of Issue 2 has been bugging me since Issue 1, and I’ve decided it’s time to make it happen (this, I admit, is also largely in part to my good friend Rey Bango’s recently renewed effort to push jQuery forward). Thankfully, the magazine’s lead designer and the team of French developers/translators have all expressed an interest in helping make Issue 2 happen, which makes this goal a lot more tangible.

Issue 1 was an experiment, and it went really well. Since it was a first though, it was very much “the Yehuda show.” I’d like Issue 2 to be more of a collaboration of contributors; there are a lot of jQuery topics to explore, and a lot of team member and users with fascinating tales to tell.

As such, I’m putting the word out there. I’m looking for contributions for Issue 2 of Visual jQuery Magazine. Articles can vary in length extensively, from brief three paragraph shorts, to three page features. They can be tutorials, feature articles, interviews and lots of other things I’m sure you’ll all think of. Just a few brief (and somewhat flexible) guidelines:

  • The article must be in magazine or newspaper format (if, in fact, your submission is a piece of writing — illustrations will also be considered). I’m extremely lax on this, but it should be something you could see being in a magazine.
  • The article must be about a topic that is timely and pertinent to the jQuery community, with broad appeal.
  • The article must not be an advertisement (but it may, obviously, feature a plugin you have written if it has broad appeal).
  • The article must be factually correct.
  • The magazine staff will edit your article for grammar, space, and style. You will receive an edited copy prior to publication for approval.
  • The magazine staff will add graphics and other visual elements as appropriate.
  • Please email a proposal or brief description of your submission before spending a chunk of time working on it; that way we can avoid running out of space and ensure that everything print-worthy gets in. Email submissions and letters to the editor to editor AT visualjquery DOT com.

    As I said from the beginning of this project, I think that the magazine has real potential to open up the jQuery world to new users, and hope that by pushing the envelope of community-produced content, we can keep jQuery moving forward in it’s current positive direction. I, for one, I’m really excited about it.

    jQuery on Rails: A (Still Very Alpha) Update

    I’ve made a number of updates to my preliminary release of jQuery on Rails:

    • It’s now in svn as part of a demo app, so you can see how it all fits together.
    • The new svn URL is http://jqueryjs.googlecode.com/svn/trunk/tools/rails_demo_app for the entire demo, or http://jqueryjs.googlecode.com/svn/trunk/tools/rails_demo_app/vendor/plugins/jquery_on_rails for just the plugin
    • I added a number of new JavaScript files to get copied when you install the plugin.
    • Your jQuery modules now need to be in app/public/javascripts/jquery_modules, which allows the core library files to be separate from your modules

    And the big news…

    I’ve written a few proof of concept helpers for jQuery on Rails that come with modules that are automatically installed in jquery_modules.

    So far, I wrote one for a tabbed interface and one for sortable tables.

    They both take the same settings as the underlying JavaScript libraries. For instance, you can set up the table sorter as follows:

    <% sortable_table :sort_class_asc => “ascending”, :sort_class_desc => “descending”, :striping_row_class => ["even", "odd"], :stripe_rows_on_start_up => true do %>
    <thead>
    <tr>
    <th>Col 1</th>
    <th>Col 2</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>jQuery 1.0</td>
    <td>$100</td>
    </tr>
    <tr>
    <td>jQuery 1.1</td>
    <td>$59</td>
    </tr>
    <tr>
    <td>jQuery 1.1.1</td>
    <td>$68</td>
    </tr>
    <tr>
    <td>jQuery 1.1.2</td>
    <td>$8</td>
    </tr>
    </tbody>
    <% end %>

    This corresponds to:

    tableSorter({sortClassAsc: ‘ascending’, sortClassDesc: ‘descending’, stripingRowClass: ['even', 'odd'], stipeRowOnStartup: true})

    You can check out both the tablesorter helper and the tabs helper in action by checking out the jQuery on Rails demo app.

    jQuery on Rails… Alpha (very very Alpha)

    UPDATE: The information in this post is outdated. Please check out the follow-up post for more details.

    I’ve posted the first release of jQuery on Rails on the jQuery svn (you can check it out at http://code.google.com/p/jqueryjs/source).

    This is a very early alpha, with fairly limited functionality, but I really wanted to get it out there so people can take a look at it (and hopefully provide feedback).

    Basically, this release allows you to modularize your JS files into related functions (say, one file for sortable tables, one file for sortable lists, etc.). Rails will then parse your completed file to determine which JS files are needed, and compile them into a single file for download. This means that you can write JavaScript files based on functionality, and not have to worry about making sure you include the exact files necessary for each page on your site. You also get the benefit of a single file being sent to the client, while avoiding the problems of sticking everything in application.js.

    Installation

    You’re going to need to download two things from trunk/tools in the jQuery svn. (1) jQuery on Rails; (2) Hpricot.

    Even if you’re already using hpricot, you’re going to need the special patched version that improves compatibility with jQuery. The plugin relies on strict compatibility, and there were a number of bugs (such as :even and :odd returning wildly different numbers of elements due to an incompatible implementation).

    To compile hpricot, you will also need ragel. If you’re on OSX, a simple sudo port install ragel should do the trick (make sure you’re on the latest version of MacPorts; you can update via sudo port selfupdate).

    After you’re done with Ragel, go into the hpricot directory and do a rake install. You’re going to get a new version of hpricot (0.5.142, which corresponds to the svn version that the patch is based on).

    You can add jQuery on Rails to your project as a plugin by doing script/plugin install http://jqueryjs.googlecode.com/svn/trunk/tools/jquery_on_rails

    Once it’s installed, you’ll need to add a route to your routes.rb file. It’s simply map.jquery (it’ll create the route that’s necessary to compile the JavaScript and run it).

    You’ll also need to add <%= include_jquery %> in your layouts. It’ll automatically include the jQuery library, some common plugins, as well as the compiled file. If you want to change the files that are included by default, edit the JQueryOnRails::JQUERY_LIBRARY constant in init.rb of the plugin.

    The plugin installation should automatically copy the necessary JavaScript files to your public/javascripts directory. If they’re not copied for some reason, just make sure you have jquery.js, interface.js, form.js, and dimensions.js.

    How to use it

    • Create a page that needs to use some JavaScript, and create a new file in public/javascripts.
    • Use a selector to select some elements on your page, and do stuff with them (that’s what jQuery’s for!).
    • Restart your web server, and navigate to the page. You should see an included JS file called app_jquery that contains your code.
    • Profit!

    What’s Next

    This is a fairly skeletal plugin. I’m going to be adding some extra caching options, so you don’t need two hits to the server for each page load.

    I’m also going to be adding some helpers, as well as a small jQuery plugin to simplify markup generation for common cases (so you’d be able to do <%= sortable_table ... do %> and stuff like that).

    Porting the existing Prototype helpers is not at the top of my list, but I might do some of the more common ones to ease in the transition.

    As always, feel free to contact me at outlookeic on AIM or wycats AT gmail DOT com with any questions!

    jQuery on Rails: A Fresh Approach

    My apologies for dropping off the face of the earth. I’ve been working hard at Procore, which I mentioned last time, and getting neck-deep in the specific problems that make working with jQuery and Rails at the same time so difficult.

    Since I last publicly discussed jQuery on Rails, I’ve gone down a lot of avenues, and written a lot of code, and came to some conclusions:

    • jQuery and Unobtrusive JavaScript are fundamentally incompatible with an attempt to describe behavior inside markup, as Rails does via “JavaScript helpers.”
    • Attempts to fix the problem, specifically UJS for Rails, still require that you include your JS behaviors in your views, which are then marshalled into JavaScript files on the fly (and cached as appropriate). If you wanted to include the same JS behavior in multiple pages, you’d need to create custom helpers and call out to them.
    • jQuery is already the perfect mechanism for unobtrusive JavaScript, baked right into the library
    • The biggest problem faced by jQuery developers is not simplicity (which, again, you get for free in the library), but difficulty in including the correct jQuery “modules” in the Rails views that require them.

    The most common problem with using jQuery with Rails in an app of moderate or higher complexity is the trade-off between including everything in a single application.js (which can lead to serious slowdowns in larger apps) and having multiple, modular files (which are a serious pain to include correctly as needed).

    This is a problem for jQuery users who want to use Rails more than Rails users who are used to Prototype helpers and want to be able to use the jQuery library as a drop-in replacement. In the first release of jQuery on Rails, I will be targeting jQuery developers who want to work with Rails. In other words, jQuery on Rails is for you if you know jQuery or are willing to use jQuery.

    This release of jQuery is not for you if you don’t want to learn jQuery, and want to program purely in Ruby. There will be a future release that will include some features for pure-Ruby developers, but I maintain that Unobtrusive JavaScript is fundamentally incompatible with that mode of thinking.

    With all that said, what does jQuery on Rails actually do?

    First up, it’s a Rails plugin, which you activate by adding <%= include_jquery %> in your application.rhtml. When your server is started, it’ll parse all of your JavaScript files, and identify selectors in those files. When include_jquery is called in your layout, it’ll get the rendered HTML and use Hpricot (which shares syntax with jQuery) to determine whether any instances of the selectors identified on server startup are present.

    The JavaScript files that have selectors that are also present in your HTML will be loaded, and run as expected.

    So in short:

    • Create your JavaScript files, using selectors as usual
    • Use include_jquery in your layout
    • You’re done

    I’ll be demoing the code at RailsConf tonight and should be releasing the first beta version sometime in the next week. If you’re at RailsConf, check out the Birds of a Feather presentation at Room c122 at 9:30 pm tonight.

    Using jQuery in Rails (Part I)

    This is the first in a series of posts about using jQuery together with Ruby on Rails. In my professional life, I work on Procore, a project management tool for the construction industry. The application is massive by any standard. And before I came on, it made heavy use of the Prototype library, Rails’ native JavaScript mechanism.

    When I came onboard, I introduced the team to jQuery, and they loved it. But it was far too much work to backtrack and remove all Prototype instances and replace them with jQuery. So our massive, complex app uses both, with no difficulties. Both libraries live side-by-side, causing no problems.

    In this series, I will discuss setting up jQuery in Rails, and some techniques I’ve developed to make working with jQuery easier in Ruby on Rails applications.

    First up, installation:

    You’ll need to download a working copy of jQuery from jQuery.com. You can either get the most recent release (recommended), or, if you’re particularly adventuresome, you can build your own copy of bleeding-edge jQuery.

    Drop jquery.js into public/javascripts, and add <%= javascript_include_tag "jquery", "application" %> to your main layout file.

    Your site will now be loading in jQuery, as well as application.js in every page (application.js is your application’s default JavaScript file and is created by default when you run the “rails” command). If you want to run Prototype alongside jQuery, use <%= javascript_include_tag :defaults, "jquery" %>. This will load in the default prototype files, application.js, and jQuery.

    In application.js, add the following:

    jQuery.noConflict()

    That will call jQuery.noConflict(), which relinquishes control of the $ alias to Prototype.

    jQuery Commands

    Virtually all jQuery commands won’t function correctly unless they’re run after the DOM has fully loaded. jQuery’s way of solving this is something called a “document ready block.”

    jQuery(document).ready(function() {
      // commands go here 
    })

    This waits until the document is ready, the fires off the function passed to ready. Here’s a shortcut syntax:

    jQuery(function() { 
      // commands go here 
    })

    This does exactly what jQuery(document).ready(…) does, but is shorter. The strategy for using jQuery in Rails is to treat JavaScript in much the way you treat CSS. You’re binding behavior, not style, to a particular set of elements identified by particular markup.

    In CSS, you might give an “a” tag the class “external” to indicate that the link goes to a page external to your site. Through a site-wide CSS page, you can then indicate that you want the tag to use a special graphic (like in Wikipedia), to illustrate to users that the link is external.

    Using jQuery, you can then indicate what behavior you want this link to have. For instance, you might the link to open in a new window. Inside the document ready block, you would use:

    jQuery("a.external").click(function() { 
      window.open(this.url, "_blank") 
    })

    I will use jQuery, not $, throughout this tutorial series, because some of you will be using Prototype alongside jQuery in your Rails apps. If you’re not, feel free to convert any instance of “jQuery” to “$”

    The above snippet will bind a click handler to all links with class “external,” and open them in a new window. And what’s great is that with JavaScript turned off, the link opens the page perfectly well, just in the same window.
    Now, let’s say you like this a lot, and want a simple Rails way to create links with the appropriate markup throughout your app (without having to train all other developers on the new markup requirements).

    You might create a simple helper in application_helpers.rb. Say, something like:

    def external_link_to name, options = {}, html_options = nil, *parameters_for_method_reference
      (html_options ||= {}).merge!({:class => "external"})
      link_to name, options, html_options, *parameters_for_method_reference
    end

    As you can see, I’ve grabbed the call signature from link_to, made some modifications to html_options (added :class => external), and then fired off a call to the original link_to.

    This is a very simple example, but this is the strategy we will use throughout this series: create some markup that is used to identify a particular behavior, instantiate the behavior via jQuery, and then, if desired, write a helper to make markup generation easier.

    Next up: Create a sortable list using jQuery and Interface. We will look at how to create the markup, write a helper, and write a single, reusable controller method to use the returned results to update a model.

    Archives

    Categories

    Meta