Friday, April 4th, 2008

GQuery: Java, GWT, and jQuery together

Category: GWT, jQuery

Are you a fan of GWT but would like toms jQuery magic mixed in? Ray Cromwell has your back, as he has created GQuery, an implementation of jQuery for GWT.

This means that you can write code like this:

  1. public void onModuleLoad() {  
  2.   $("div").css("color", "red").click(new Function() {  
  3.      public void f(Element e) {  
  4.        Window.alert("Hello");  
  5.          $(e).as(Effects).fadeOut();  
  6.       }  
  7.    });  
  8. }

I decided to demonstrate some of the huge benefits of 1.5 by implementing a type-safe JQuery clone in GWT.

That’s right, for all those folks who don’t want to deal with GWT Widgets, but just want to query, wrap, and manipulate plain old DOM elements in GWT, this article is for you. I’m talking to you, you self-hating Java programmer with an inner Javascript Ninja begging to be let out.

After the GWT compiler gets its hands on it, the example comes in at 5459 bytes. This library can only be achieved with GWT 1.5 features, and gives you:

  • Joel Webber of the GWT Team just submitted a patch to GWT 1.5 that implements every DOM2 Core+HTML class as a subclass of the new JavaScriptObject. This not only made the coding of GQuery very easy, but it produces nicely optimized JavaScript.
  • Static Imports. The $ function would not nearly be as nice without static imports.
  • Generics and Covariant return. The Plugin mechanism utilizes this to fake prototype based overrides of the GQuery object.

Fun little feature, $$

jQuery contains a lot of methods which take essentially property/value pairs in a Javascript object literal. Emulating this with Java syntax would be too tedious (Scala frontend to GWT, please!), however, to ease this use case, I added a global $$ function for manipulation JavaScriptObject/JSON objects easily.

  1. Properties literal = $$("{ foo: 'bar', baz: 'bam'}");  
  2. $$("{foo: 1, bar : 2}").get("foo") == 1;

Posted by Dion Almaer at 12:15 am
Comment here

3.9 rating from 24 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.