Archive for the 'Programming' Category

I’ll Buy That!

So it has been a few weeks since Apple announced the iPad. I was pretty excited when I saw it, but gave it some time to digest what everyone else was saying and also the implications. The iPad definitely has its detractors, with most somehow working a feminine hygiene joke into their rants. But in the end, I’ll happily be first in line to buy one. Why?

The game changing aspect of the iPad is Safari. There will be plenty of cutesy apps, but I would sooner chew my own arm off than work with Objective-C. It is a disgusting abomination of a language. But having Safari on the iPad means developing feature-rich RIAs in HTML 5, with fast JavaScript, that can be packaged to deploy so that they appear the same as other iPad/iPhone applications (Dock icons, etc…). Best yet, Apple is giving the finger to Adobe and Flash. The iPad is going to put a nail in the coffin of Flash and help advance web standards by leaps and bounds.

Yehuda Katz of the jQuery team summarized it best in this blog post. I completely agree with him. The iPad is a godsend for HTML and JavaScript developers and anyone who values open web standards should be doing back flips right now. A thin tablet device with a cutting edge browser and wireless networking is going to open up a world of vertical market possibilities for web developers. I was really impressed with what Graham Glass did with his iPhone web application for EDU 2.0, and can only imagine how an application like this could take advantage of the iPad.

Check out the Safari Developer Documentation on Apple’s site sometime to really understand the vast programming playground Apple is creating for us. I’m actually excited about web development for the iPad and am looking forward to getting mine to play with.

Rails Flashback

While poking around one of the Ruby on Rails sites, I stumbled upon the video of DHH’s keynote at RailsConf 2009. Rails 3 looks really cool, but DHH has definitely mellowed from the 2006 and 2007 RailsConfs I attended. Just watching the keynote brought back some good memories of the 2007 RailsConf.

RailsConf 2007 was held in Portland, Oregon, which is about the most awesome city I’ve been to for a conference. It has all the amenities of a big city, but still keeps a quirky small town feel. Between the conference, awesome micro-brews, and Powell Books, it was a really good time.

This was the RailsConf I went to with my Windows notebook while 99% of everyone there was running on a MacBook, so I played the leper. The speakers were great, and it was absolutely hilarious when one of the vendors had the Extra Action Marching Band show up at lunch the first day to perform. It pissed off the stodgy convention center management, but it was a sight to see. Check out James Duncan Davidson’s excellent photos if you want to see how fun a RailsConf could be.

I was thinking of going to RailsConf this year, but it is in Baltimore. I’ve never been a fan of east coast conferences, and I’m worried RailsConf is losing its fire. Just like JavaOne tapered off in to boredom, RailsConf on the east coast could be its jump the shark moment. But if they ever get around to having it in Portland again, I’ll be there.

Cool CBT

After enough time in technology, one tends to become pretty jaded about vendor claims. I’ve seen enough miracle solutions before, most them involving code generation to “eliminate the developer.” It has gotten to the point that if I even hear a vendor mention SOA, I whip out a can of Bear Mace and let them have it.

So it came as a great personal surprise when I actually saw a vendor demo for something both cool and practical. I sit on the .NET Center of Excellence for our oversized company, and part of the role is listening to vendors show off their latest and greatest. Our last demo was from a company called InnerWorkings and I had honestly never heard of them before the demo.

InnerWorkings has an incredibly awesome computer-based training (CBT) system for learning .NET. It goes beyond book reading and is heavily based around coding exercises which are even scored by the system. It has a Visual Studio plugin for working with the vast library of learning material and links to O’Reilly’s Safari Books for reference.

I had never seen a CBT product before this which I would actually considered to be effective. This looked good enough that I would almost be willing to invest my own dollars. If you need to bring a development team up to speed on .NET programming, or a specific area on the bleeding edge, I highly recommend taking a look at InnerWorkings.

(Ext.)Direct Miss

One of the biggest announcements from last month’s ExtJS Conference was the new Ext.Direct functionality in ExtJS 3.0. My criticism at the time was that there was a lot of smoke, but no fire. Almost every session mentioned it in some way or another, but they weren’t producing any enterprise-worthy server code showing how it is implemented.

Now, a month later, more details are starting to emerge, including implementations for various technologies. I sat down yesterday morning intending to take a look at the server side code in the Ext.Direct Pack; in particular the .NET and Java implementations. I was pretty disappointed with what I saw.

To understand my disappointment, you need to understand a bit of history around what Ext.Direct is attempting to do. Ext.Direct is going to be an RPC layer that exposes stub objects on the client JavaScript side that remotes the method calls to the server using JSON (or POST parameters). The protocol definition is designed to be technology-agnostic and easy to implement. In implementation, it would be the near-equivalent of DWR, except it would also run on PHP, C#, Ruby, etc…

Since I’m familiar with CORBA, RMI, SOAP and WCF, I approached Ext.Direct with a more critical eye. The biggest glaring hole in Ext.Direct is the parameter passing. Let’s take a look at a couple examples to demonstrate the problem. All the examples will assume a Java backend, and the service we’ll expose is the PersonService. I’ll work from the interface, since we don’t care about the implementation details:

public interface PersonService {
 
}

Easy

We’ll add a method to PersonService to demonstrate the simplest scenario:

public int getPersonCount();

The payload from Ext.Direct would look something like this:

{ "action":"PersonService",
   "method":"getPersonCount",
   "data":[],
   "type":"rpc",
   "tid":2}

This is the absolute easiest method to deal with. The operation takes no parameters, and the return value is a primitive. Ext.Direct can deal with this easily, but so could any AJAX library, so no secret sauce here.

Object

One of the key advantages to an RPC protocol is the ability to pass Objects. Well complicate things a bit by adding the following method to the PersonService:

public Person getPerson(int id);

For our example, we’ll assume the Person class looks like this. I’m not including setters/getters to try and keep it short:

public class Person {
  private int id;
  private String name;
  private int age;
  private Date birthDate;
}

In the method I added above, the JSON payload from Ext.Direct stays pretty simple:

{ "action":"PersonService",
   "method":"getPerson",
   "data":[1],
   "type":"rpc",
   "tid":2}

This should return the Person with the ID of 1, and depends on the server code to correctly serialize the Person object to JSON.

Harder

Now let’s make things painful. I’m going to include a method to add a Person.

public void addPerson(Person person);

This is where the wheels fly off of Ext.Direct. Since the protocol specifies the data element as an array, I’m not clear on how Ext.Direct would deal with this from the client side. Every example so far works with primitives as parameters, so I haven’t determined what it would do with a Person.

Ext.Direct would be much happier if I defined the addPerson method like this:

public void addPerson(int id, String name,int age, Date birthdate);

Then, the JSON payload would look like this:

{ "action":"PersonService",
   "method":"addPerson",
   "data":[1,"John Doe", 25, "Sun May 01 1985 00:00:00 GMT-0500 (Central Daylight Time)"],
   "type":"rpc",
   "tid":3}

Even in this “happy path” scenario for dealing with an object, your server-side implementation would need to be able to correctly deserialize the stringified javascript date object, which is not anything the current implementations handle.

The protocol specification states that the data element can also be a JSON object with named parameters, but it is not supported in the first implementation. This is going to be absolutely critical if Ext.Direct is going to evolve into a real RPC protocol. For example, using a JSON object for the data element in the above example would result in a JSON payload like this:

{ "action":"PersonService",
   "method":"addPerson",
   "data": {id: 1,
           name: "John Doe", 
           age: 25, 
           birthdate: "Sun May 01 1985 00:00:00 GMT-0500 (Central Daylight Time)"},
   "type":"rpc",
   "tid":3}

This would at least allow the server code a means to try and instantiate an instance of the Person object, as long as the server code is implemented in a language that allows for reflection of the Object.

My grief with Ext.Direct is that correctly implementing the server-side code to support the specification is a non-trivial endeavor. One big piece missing is the metadata. In other RPC mechanisms, there is strongly-typed metadata which can be used to create the stubs. For example, CORBA has IDL and SOAP has WSDL.

Ext.Direct is missing a metadata layer to facilitate the passing of Object values. It is going to be difficult to implement a complete server-side stack to handle the permutations that will arise. Developers will either need to dumb-down the exposed services to handle the limitations of Ext.Direct, or else they will end up doing a lot of custom work on top of the server side implementation to handle the type coercion.

I’m still not convinced Ext.Direct is the right path for ExtJS to be barking down. There are already established, tested protocols for handling RPC via JavaScript (DRW, WCF), and ExtJS already works quite well with basic AJAX over the HTTP protocol. Ext.Direct is adding a level of complexity to ExtJS which could easily turn into a rabbit hole that sucks up all their time. I would prefer they focus their precious development hours on the client library and leave the communication layers decisions to us. RPC is a complicated problem with a lot of history around it, and there is no reason for them to try and invent a new wheel in this space.

Flexible Spring

As I mentioned in my prior post, I’ve been going through the great Flex in a Week from Adobe. I finally hit Day 3 and had a need to play with BlazeDS for the second lesson. Being a fan of the Spring Framework, I decided to use the recently released Spring Blaze DS Integration 1.0rc1 (Spring-Flex). This ended up turning in to a bigger beatdown than I expected, for several reasons.

I really wanted to use the Spring-Flex integration because I like the annotation-driven dependency injection option that Spring brings to the table. Unfortunately, I could not find a single comprehensive document or example showing how to setup a project from end-to-end using Flex and Spring-Flex. I started with my Spring template project, adding in the BlazeDS dependencies and configuration. I then stripped out the stuff I didn’t care about for this example. Then I went digging through the various reference guides and blog posts trying to figure out the correct configuration I needed on both the Java and Flex side.

After about three days of hair pulling, the pieces finally started to fall in to place. Once I understood the configuration, it became a breeze to configure services to be exposed by Spring-Flex and to call those services from Flex via a RemoteObject. I’ve linked the complete Java project and Flex project archive below:

Spring-Flex Project

Flexbuilder Project Archive

There is a README.txt file in the root of the Java project directory that walks through the setup. This project is configured to talk to a MySQL database using an iBatis DAO layer and includes the setup scripts, all run from Ant. The build file also makes use of Ivy to grab dependencies, thus reducing the number of jars I have to include.

The Flex project is configured to talk to the exposed employeeService on localhost, so you’ll need to change the configuration of the RemoteObject if you want to point to a different destination.

Here are some of my lessons learned that will hopefully help others:

#1: Life is easier if you keep BlazeDS’s services-config.xml file in the default location: WEB-INF/flex/services-config.xml. The version of this file that comes with the BlazeDS turnkey download has a small problem. It does not specify default channels, which is what FlexBuilder will use to figure out what is going on. Look at the version I have in the Java file and notice at the top:

<services>
  <default-channels>
    <channel ref="my-amf" />
  </default-channels>
</services>

You’ll want this in your services-config.xml file if you plan on specifying an application server in FlexBuilder.

#2: And on the subject of application servers, you actually don’t even need to specify the server technology. I built my solution as a standalone Flex project with a standalone Java project and had the two talking together without a problem.

The secret to making it work is in how you configure the RemoteObject in FlexBuilder. Here is the configuration for my RemoteObject:

<mx:RemoteObject id="employeeRO" 
  destination="employeeService" 
  showBusyCursor="true"
  fault="handleFault(event)">
  <mx:channelSet>
    <mx:ChannelSet>
      <mx:AMFChannel id="amf" uri="http://localhost:8080/flex/messagebroker/amf"/>
    </mx:ChannelSet>
  </mx:channelSet>
  <mx:method name="getEmployees" result="allEmployeesHandler(event)"/>
  <mx:method name="doCreate" result="employeeHandler(event)"/>
  <mx:method name="doUpdate" result="employeeHandler(event)"/>
  <mx:method name="doDelete" result="employeeDeleteHandler(event)"/>
</mx:RemoteObject>

Specifying the ChannelSet enables you to take control of where the RemoteObject is binding to instead of relying of FlexBuilder magic. Just change the URI to point to the correct location.

There is one little catch. You need to set the FlexBuilder build output directory to Tomcat’s webapps/flex directory (after you have deployed the war file), or you’ll get a security exception about breaking out of the sandbox. I’m guessing that the flex file is looking for the services-config.xml file to figure out what it is supposed to do, and if it is not in the correct directory relative to the SWF file, your application will barf. So deploy the flex.war file from the Java project first, then play with the flex half of it.

#3: Once you have the dependencies sorted out, configuring the Flex broker is literally a one-line configuration option. Check out web/WEB-INF/flexDispatch-servlet.xml in the Java project and notice this line:

<flex:message-broker />

That’s all you need. Really. This one line of config uses “sensible defaults” to initialize BlazeDS. It will read services-config.xml from the default location (see tip #1) and setup the endpoints for you based on the configuration.

#4: I’m a fan of annotation-driven configuration for Spring, and Spring-Flex does not disappoint. Here is the implementation of the EmployeeService class:

@Service("employeeService")
@RemotingDestination
public class EmployeeServiceImpl implements EmployeeService {
 
    @Autowired
    private EmployeeDao employeeDao;
 
    @RemotingInclude
    public List<Employee> getEmployees() {
        return employeeDao.getEmployees();
    }
 
    @RemotingInclude
    public Employee getEmployee(String id) {
        return employeeDao.getEmployee(id);
    }
 
    @RemotingInclude
    public List<Employee> getEmployeesByDepartment(String department) {
        return employeeDao.getEmployeesByDepartment(department);
    }
 
    @RemotingInclude
    public void doCreate(Employee employee) {
        employeeDao.createEmployee(employee);
    }
 
    @RemotingInclude
    public void doUpdate(Employee employee) {
        employeeDao.updateEmployee(employee);
    }
 
    @RemotingInclude
    public void doDelete(Employee employee) {
        employeeDao.deleteEmployee( employee.getId() );
    }
}

The top @RemotingDestination tells Spring-Flex this is a service that is going to be exposed via BlazeDS. You can provide an optional parameter specifying which channels to use, if you have several configured. Then, each method you want to expose is annotated with the @RemotingInclude annotation. Methods that should not be exposed can be annotated with the @RemotingExclude annotation.

So if you’re following along with Flex in a Week, or have just been trying to get Spring-Flex up and talking to a Flex application, give the demo a try and look over the source code. This corresponds to the second video of Flex in a Week, Day 3. I wish I would have known some of these things starting out, so hopefully I can save other people some time.

Flex in a Week

One of my unexpected take-aways from the ExtJS conference last month was that I need to start looking at Flex again. This isn’t necessarily for the Flex framework itself, but because of AIR. I’ve started to see a lot more AIR applications popping up, and my Twitter client (Twhirl) is even AIR based. ExtJS with AIR makes for an extremely powerful combination.

So to build a foundation for AIR, I decided to learn Flex. After a strong year of JavaScript, Flex starts to make a lot more sense from a syntax standpoint. And ironically, the best way I’ve found to learn Flex is free: Flex in a Week.

Adobe has produced a truly outstanding series of video training classes for Flex. Although it is structured as five days worth of materials, I’m only getting through half a course each day due to quiet time constraints with a two-year old in the house. I have been very impressed with the quality and level of detail. The videos aren’t full of fluff and get quickly to code. There are exercises interspersed with the training videos, but I’ve passed over them, opting instead to follow along with the videos.

The only downfall to my choice to follow the videos instead of the exercises is that Adobe didn’t make it easy to find some of the supporting pieces you need to follow the videos. For example, there is an XML data file called employees.xml used for a lot of the code in the videos that is nowhere to be found. Ultimately, I found a CSV version of the data file in an AIR Sample, along with the images used for building the employee directory application.

In the interest of helping out others who start on Flex in a Week, here are the supporting files necessary for following along with the code. I’ve only finished the second day, so I’ll try and add any additional parts I find missing.

  • employees.xml – the XML data file with the employee information (right-click to save it)
  • headshot images – the thumbnail images for the directory, both normal and small sized

I’m hoping to finish up the tutorial this week and jump into more complex things with Flex. I’ve been very impressed so far, although not enough to eat crow yet on my negativity towards Flash in general.

What about Flex books? I picked up Programming Flex 3: The Comprehensive Guide to Creating Rich Internet Applications with Adobe Flex and it has been a total disappointment. The book is very poorly structured and it jumps all over the place without a coherent plan. It swings between excessive detail of the Flash engine, followed by trivial, poorly explained examples of the Flex widgets. I may find value in it later as a reference, but am dumping it for now.

I did pick up another book that I really like a lot: Learning Flex 3: Getting up to Speed with Rich Internet Applications (Adobe Developer Library). This one is well structured and gets to the things I’m interested in, not the nitty-gritty details of the Flash player. I would recommend this one for anyone who is at a similar point in their Flex learning experience.

Beyond the Core

In my earlier post, I compared the new Ext Core JavaScript library with JQuery to demonstrate how close they are on core functionality. I explicitly kept the scope narrowed down to areas where the two libraries overlapped, and my conclusion was that both are winners but I prefer Ext Core since I use ExtJS and prefer the coding style.

In this post, I want to get in to demonstrating some of the features of Ext Core that are either coded differently from JQuery or that the base JQuery library does not implement. The excellent Ext.Core manual has more detail on all the functions, so I’ll just bring attention to some of cool functionality I like.

Base Class Enhancements

One feature that might be controversial for some developers is that Ext Core augments some of the base JavaScript objects to ensure some features are present across implementations and to add some useful helper methods. The JavaScript Augmentation section of the manual has details on all the enhanced methods. Function, Array and String are the three base objects that get augmented.

For example, the String object is augmented with a static format() method that essentially allows the String to function like a typical printf function:

var dest = 'World';
var greeting = 'Hello';
var msg = String.format('{0}, {1}!',greeting, dest);
// msg contains "Hello, World!"

The Array object is augmented with indexOf() and remove() methods, and the Function object itself picks up several OO-centric functions.

The reasoning behind the augmentations are in the manual. I have mixed feelings on augmenting the language’s base objects, but the features are appreciated.

Namespaces

Using a namespace mechanism so that all your variables don’t pollute the global namespace is something every JavaScript coder should be doing. There are plenty of code snippets out there to demonstrate how this is done, but Ext Core makes it easy for you by including namespace support as a part of the library. All this is handled through the Ext.namespace() static method.

Take a look at the sample below. The comments indicate the filenames:

// first.js
Ext.namespace('First');
First.name = 'Tim';
 
// second.js
Ext.namespace('Second');
Second.sayHello = function(name) {
    alert( String.format('Hello, {0}',name) );
};
 
// main.js
Ext.onReady(function() {
	Second.sayHello( First.name );
});

The three JavaScript files don’t even need to be imported in this order. Everything happens through the namespace references declared at the tops of the files and managed by Ext Core. In this case, objects called First and Second were created under window, and the sayHello method and ‘name’ variable were placed under them. This means our code only added two variables to the global space. This didn’t make a difference with only two variable declarations, but can have a huge impact with a typical application.

Namespaces can be hierarchical, so you can limit the global pollution to a single entry. For example, you can define a namespace like this:

Ext.namespace('Application.Init');

Ext Core will create all the intermediate namespaces, so you could places variables under both Application.Init and Application with this single declaration. This provides a similar naming hierarchy to what you would find in Java packages or C# namespaces.

Encode and Decode

Ext Core provides helper methods to encode and decode both JSON and URL-encoded data. The Ext.encode and Ext.decode will encode or decode JSON objects to and from Strings. This is useful for the AJAX methods, as I demonstrated in my other post. In the current beta, the encode and decode methods aren’t implemented yet, but they are in the documentation, so I’m expecting to see them before the final release.

The Ext.urlEncode and Ext.urlDecode methods will encode or decode JSON objects to URL-encoded strings. One typical example is to decode query string parameters. For example, if the page URL was this: http://mycoolapp.com?name=Tim&lang=Java, you could easily decode the query string into a JSON object using this snippet:

var params = Ext.decode( document.location.search.substr(1) );
alert( String.format('Hello, {0}', params.name) );

Yes, this is a bit of a hack. I didn’t do error checking to ensure there was a value for search before using substr(). The substr() is necessary when working with a query string because the search value will start with a question mark (?), which the Ext.urlDecode method won’t strip off.

Templates

Ext Core thankfully includes Templates, a feature generously carried down from ExtJS. Templates simplify the repetitive generation of HTML fragments, which is something that typically happens in AJAX intensive web application. The Ext.Template class allows you to define an HTML fragment as a template, using tokens which will be replaced with the values from a JSON object. For example, here is a code sample of a Template used to format an RSS feed from Slashdot that I turned into a JSON object:

// Feed.data is an array of JSON objects that look like this:
// {title: 'title', link: 'link', description: 'description'}
 
var template = new Ext.Template(
            '<div class="story">',
            '<h3><a href="{link}">{title}</a></h3>',
            '{description}',
            '</div>');
 
// stories is the id of the empty div on the page
var stories = Ext.get('stories');
 
Ext.each(Feed.data, function(item) {
    template.append(stories, item);
});

This snippet also demonstrates the Ext.each() helper method for iterating over the contents of an array. You can download the full snippet here to play with.

As Ext Core is still in beta, there is a disconnect between the API documentation and the actual implementation. If the Ext.Template class is updated to correspond to the documentation, there are also some neat formatting effects that can be applied. For example, instead of the placeholder {description}, you could use {description:ellipsis(20)} which will truncate any string longer than 20 characters and place ellipsis at the end of the string.

I’ve covered a few of the cool features to make your JavaScript code easier and more maintainable. Ext Core also has some neat OO functionality that I’ll cover in another post.

New Kid on the Block

On this cloudy Dallas Saturday morning, the ExtJS team announced the availability of Ext Core (beta). Ext Core is the core DOM selection, manipulation and events library of ExtJS which has been extracted out into a separate library released under a more liberal license. They smartly released this under the very permissive MIT license, in contrast to the cancerous GPL used for the full ExtJS.

What makes this interesting is it positions Ext Core as a direct competitor to the popular JQuery library. I really like both ExtJS and JQuery, so I decided to run a quick comparison of the two libraries to see if Ext Core is up to the task of replacing JQuery in my developer toolbox. Since there is so much overlap between the two, it makes no sense to use both.

Round 1 – Size

Library size of the two is pretty close. The minified version of JQuery runs about 56K, while the minified version of Ext Core weighs in at 75K. The 19K difference might matter for an iPhone application, but even then, I would consider it negligible. Both are pretty small libraries, so we’ll call Round 1 a tie and move on to feature comparison.

Round 2 – Load Event

How each of these libraries works the document ready event is more a matter of style. The JQuery convention is to use the dollar sign ($) for for operations, although you can fall back to using the full name (jQuery). Setting up a ready event in JQuery looks like this:

$(document).ready(function() {
    // do cool stuff
});

Ext Core uses the static Ext class for the same functionality. Like the jQuery object, the Ext object is the heart of Ext Core. Setting up the ready listener in Ext Core looks like this:

Ext.onReady(function() {
    // do cool stuff
});

One big difference is the onReady method can take an additional parameter specifying the scope in which the onReady method should execute. This is not a big deal in most cases, but shows Ext Core’s attention to support object oriented JavaScript. Since I’ve never actually needed to specify the scope, I’ll call this round a tie too.

Round 3 – Selectors

This is the heart of both libraries, and a full comparison could fill a dozen pages. The short story is they both support basically the same set of CSS3 selectors along with some custom enhancements. From looking at the documentation, I couldn’t find any typical use cases that either couldn’t handle. Like the document ready example above, it just comes down to a matter of convention. For example, here is the code from each to add a class to a set of nodes:

// JQuery
$('td.age').addClass('someclass');
 
// Ext Core
Ext.select('td.age').addClass('someclass');

One major style difference between the two is that Ext Core has a tighter focus in handing elements with ids, since that is critical to the full ExtJS library. For example, Ext Core has the get() method to directly grab an element by ID, along with a memory-friendly fly() method. The fly() method does not create a new element wrapper in memory, and instead reuses a single global element object. This can save a lot of memory when you just need to do quick manipulations of single objects.

// Add a class to the element with ID of 'header'
Ext.fly('header').addClass('someclass');

For the memory saving fly operation, I’ll give the advantage to Ext Core, although they are essentially equal in their DOM selection abilities.

Round 4 – Events

Like the selectors above, there are basically style differences between the two libraries in how they handle basic event use cases. JQuery adds some methods to the jQuery object for registering common events. For example, here is the code to add a click event to a button for each, including the JQuery shortcut:

// JQuery with bind()
$('#myButton').bind('click', function() { alert('Clicked');});
// JQuery with shortcut
$('#myButton').click(function() { alert('Clicked');});
// Ext Core
Ext.fly('myButton').on('click', function() { alert('Clicked');};

JQuery brings some some additional enhancements to the game in the form of “live” events. This provides a way of attaching an event to all current, and future, instances of the selector. JQuery also supports event namespaces, where events can be fired in a hierarchy. Both are powerful concepts, but I’ve never had to use either.

The secret sauce for Ext Core is in extended configuration. With Ext Core events, you can also configure the scope (a common Ext Core theme), along with configuring the event propagation, extra parameters, and a delay. Here is a sample of a click event configured with ‘this’ scoped to the onClick event itself, to only fire once (single), with a delay of 100ms and an additional parameter (forumId) to be passed to the event handler:

el.on('click', this.onClick, this, {
    single: true,
    delay: 100,
    forumId: 4
});

So again, I’m going to call this round a tie. Both libraries handle simple event binding very easily. If you need the live events, the nod goes to JQuery. If you need the extra configuration options, Ext Core is your best bet.

Round 5 – DOM Manipulation

Once again, the two libraries provide a near complete overlap of basic DOM manipulation functionality. Each can easily create, move, add and insert DOM elements.

JQuery aims for convenience. For example, one feature of JQuery I really appreciate are simple methods to clear the content of a DOM element and set the text. For example, given:

<div id='message'>First Message</div>

With JQuery, it is simple to update the text:

$('#message').text('New Message');

The text() method removes all the child nodes of the matching elements and appends a text node containing the specified text. The text() method without a parameter will retrieve the text for a matching element. For Ext Core, you have to drop down to the DOM to set the new text value:

Ext.fly('secret').dom.innerHTML = 'New Message';

The Ext.Element class does not provide simple methods for setting the text or removing all the children of an element, which I find to be an annoying inconsistency.

On the plus side, Ext Core provides a lot more methods for manipulating the DOM. One of the cool ones is the radioClass() method. This method will add a class or classes to an element and remove that same class (or classes) from all the siblings. For example, here is a simple table with a row having the ’selected’ class:

<table class="data">
    <thead>
        <tr><th>Name</th><th>Age</th></tr>
    </thead>
    <tr>
        <td>Bill</td><td class="age">20</td>
    </tr>
    <tr class="selected">
        <td>Alice</td><td class="age">21</td>
    </tr>
    <tr>
        <td>Jeff</td><td class="age">22</td>
    </tr>
    <tr>
        <td>Susan</td><td class="age">23</td>
    </tr>
</table>

This one line of Ext Core code will remove the ’selected’ class from the current TR element and add it to the first row in the table:

Ext.select('table tr:first').radioClass('selected');

So for this round, I’ll give the advantage to JQuery for the more consistent API, especially around manipulating the text nodes of an element. This is something pretty simple for Ext Core to address, which they really should. Ext Core does, however, offer more powerful DOM manipulation options.

Round 6 – Effects

I’m not a big effects junkie, so I won’t have a lot to say about this. Both Ext Core and JQuery provide a very similar set of effects for elements (hide/show, fade, slideIn/Out, etc…). Ext Core provide a more powerful API for creating custom effects, while JQuery addresses this with its rather extensive set of plug-ins. I’m calling this one a tie.

Round 7 – AJAX

Ext Core and JQuery both make AJAX simple, but again, we’ll see that JQuery adds more simplified methods while Ext Core offers more powerful configuration. Here is a sample of an AJAX call that returns JSON data:

// URL returns a JSON object like this: {name: 'Tim'}
 
// JQuery 
$.getJSON('http://myurl', function(data) {alert(data.name);});
// Ext Core
Ext.AJAX.request({
    url: 'http://myurl', 
    success: function(response) {
        var data = Ext.decode(response.responseText);
        alert(data.name);
    }
});

JQuery provides the simplified getJSON() method where the parameter to the callback has already been decoded into a JSON object. For Ext Core, the callback receives the XHR response object and you have to decode the text to JSON.

The Ext Core request() method demonstrates a typical ExtJS convention of using a JavaScript configuration object as a parameter instead of using multiple parameters.

Both libraries provide strong AJAX support, so we’ll go with a tie for this round too.

Round 8 – Documentation

There is no contest in the documentation department. While the JQuery documentation has improved, the Ext Core documentation blows it away. From the excellent manual to the high-quality API documentation, Ext Core sets the standard for what all documentation should look like.

Round 9 – Intangibles

For JQuery, the biggest intangibles are its plugins and support from Microsoft. JQuery is intentionally designed to provide a simple core set of functionality and to be easy to extend. There are hundreds of plugins people have written for JQuery in the Plugin Repository. As with all things open source, some are very good and some are kinda crappy, but you can be pretty certain to find a plugin that covers about anything you might be trying to do that is not covered by the core JQuery API.

Microsoft support is also a biggie. They have decided to include JQuery as a base JavaScript library in their web tools going forward. This means you won’t need to get special blessings to use JQuery in large corporate environments — it will be part of the core Microsoft bundle, with support and all.

Ext Core, being brand new, is lacking in both community and support. Ext LLC, the company behind ExtJS and Ext Core is a small software shop trying to get by in a tough economy. While their products are cutting edge, I’m expecting them to be bought out by a larger company before too long. I keep trying to talk my Spring Source contacts into buying them, but I have a feeling they’ll be bought by Adobe.

So from an intangibles perspective, JQuery is the winner. It is guaranteed to have longer legs under it, at least until we see where Ext LLC ends up.

Conclusion

Both Ext Core and JQuery are solid, complete base JavaScript libraries. JQuery leans towards simplicity while Ext Core offers enhanced configuration. The choice of which to use will come down to where you are now.

  • If you use JQuery, and don’t anticipate using ExtJS, stay where you are. You’ve got a winner.
  • If you use ExtJS and have used JQuery as a light weight option for when you didn’t need the widget library, Ext Core is now your library of choice.
  • If you are in search of a JavaScript library, the choice is tougher. Unless there is a particular JQuery plugin you want to use, I recommend going with Ext Core. It starts laying the groundwork for using ExtJS, which you’ll want to do as you get in to building RIAs.
  • If you’re a corporate Microsoft shop, you probably don’t have a choice. JQuery is now something you can slip by the infosec police without making waves.

Ext Core is definitely a winner. In the past, I have used JQuery for projects that need simple DOM manipulation and ExtJS for when I need the widgets, layouts, etc… Now that I have Ext Core, I don’t see using JQuery anymore for the simple cases. I can standardize on using the same API paradigm between Ext Core and ExtJS.

Follow-up #1: Beyond the Core
Follow-up #2: Slick Speed

ASP.NET MVC 1.0

I’m not sure why Microsoft is being so quiet about it, but they have apparently released the ASP.NET MVC 1.0 final. Kudos to Caleb for tipping me off via a random tweet.

I went fishing all over yesterday and didn’t find any big release announcements. I expected Scott Guthrie to have something on his blog, but nothing yet. The MSDN site finally had a release announcement this morning.

This is fantastic news for .NET web developers. This finally gives ASP.NET a production-ready web MVC framework distributed by Microsoft. This framework is the future of ASP.NET.

Getting Groovy

As we get more into our project at Orange Leap, we’re starting to see a lot of instances where a dynamic language would make our life easier. On all of our entity classes, we associate a map of custom fields. The custom fields are so that clients can customize the entities without us having to change the code each time. The custom field definitions go beyond basic key-value pairs and can include references to other custom fields. For example, spouse is a custom field that relates two entities and is bidirectional. If you open either entity, you’ll see the other in the spouse custom field.

A dynamic language would come into play in that we could access all the attributes of an entity in a consistent way, preferably through dot notation. Since we’re already running on top of Java 6, Groovy came to mind as the best candidate for a dynamic language.

I’ve never really played with Groovy before. I mostly played with Ruby and Rails, which really opened my eyes to the power of a good dynamic language. Some of the developers on my team wanted to get into Groovy while I was at Countrywide, but I kept us out of it for fear of ending up with an unmaintainable monster if one of the experts left. (this is actually the primary motivator in 99% of all enterprise technology decisions — the bus factor)

So this week I finally jumped in with both feet and I have to say I like what I found. Everything cool I liked about Ruby and .NET 3.5 was in Groovy. Metaprogramming, check. Mixins and Closures, check. Full access to all the JVM goodness, check. The recently released Groovy 1.6 even goes beyond Ruby and .NET 3.5.  For example, if you tag a class with the annotation @Singleton, it turns it automagically into a singleton.

@Singleton
class Friend {
    def name
}
f = Friend.instance
f.name = "Tim"
print "Hello, $f.name"

If you try and call new on the Friend class, you get an error that you can’t instantiate a Singleton. All this handled with a simple annotation. For an excellent overview of all the coolness in Groovy 1.6, check out this article on InfoQ.

So I’m going to keep working my way through Programming Groovy and am eager to start applying what I learn. And best of all, my favorite IDE has the industry’s best support for both Groovy and Grails.