Solving Cross Browser Issues - Part 2 (GWT and Dart)



In the previous part of the post I had a look at combatting cross-browser issues using JQuery and gave a quick introduction to the GWT (Google Web Toolkit).

For those of you that came in late, cross-browser issues refers to the issues that arise due to the fact that the browser creators are inclined to implement the web standards differently.

In this post I am going to take the criteria used in the previous post and show you some source code examples of how to use GWT and Dart (bear in mind that Dart is unstable and still in its pre-infancy).


The GWT SDK is available over here and the Dart SDK over here.


GWT



I don't code in Java all that often and in addition this is the first time I've attempted using the GWT, but I found it (version 2.4) fairly straightforward to use, look at the following Java snippet:

 
package firstdemo.client;
 
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.*;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.ui.TextArea;
 
public class FirstDemo implements EntryPoint {
public void onModuleLoad() {
	NodeList<Element> textareas =  Document.get().getElementsByTagName("textarea");
 
	for(int i = 0; i < textareas.getLength(); i++)
	{	
		final TextArea textarea = TextArea.wrap(textareas.getItem(i));
		final String maxlength = textarea.getElement().getAttribute("maxlength");
 
		if (!maxlength.isEmpty())
		{
			textarea.addKeyPressHandler(new KeyPressHandler()
			{
				public void onKeyPress(KeyPressEvent event)
				{							
					int keyCode = event.getNativeEvent().getKeyCode();
					if (((keyCode == KeyCodes.KEY_BACKSPACE) || (keyCode >= KeyCodes.KEY_LEFT)  && (keyCode <= KeyCodes.KEY_DOWN))
							|| (textarea.getText().length() < Integer.parseInt(maxlength))) return;		
					event.preventDefault();
				}
			});
			addPasteHandler(textareas.getItem(i), maxlength);
		}
	}	
}
 
	public native void addPasteHandler(Element element, String maxlength)
    /*-{
        element.onpaste = function(e) {
			setTimeout(function()
			{
				if(element.value.length > maxlength) {
					element.value = element.value.substring(0, maxlength);
				}							
			}, 1);
 
        }
    }-*/;	
}
 


Like previously we iterate through all the textareas on the page and attach event handlers wherever we find the maxlength attribute.

Now Google states that "GWT shields you from worrying too much about cross-browser incompatibilities. If you stick to built-in widgets and composites, your applications will work similarly on the most recent versions of Internet Explorer, Firefox, and Safari. (Opera, too, most of the time.)"

Unfortunately I couldn't stick to the built-in composites since the required paste event is excluded from the GWT, likely because its not completely supported by all browsers, which forced me to make use of the JSNI (see addPasteHandler method).

Thanks to the JSNI I was able to add my browser specific code, but also add code that won't work in all browsers - the paste event wont be fired by Opera for example.

Which makes me inclined to go as far as to say that you must steer clear of the JSNI if you're interested in writing cross-browser friendly code.

All in all it does however feel like a helluva lot of extra code to write if you compare it to something like JQuery, but I nevertheless started liking GWT over the last few weeks.

Dart



If you're unfamiliar with Dart, its basically a new language that Google is busy developing for the web, very similar to JavaScript - I think of it as JavaScript on steroids (or the next step in evolution of JavaScript).

But just like GWT (currently at least) it compiles to JavaScript and in fact many of the developers that worked on GWT are busy working on Dart.

At the moment its not much of a cross-browser solution as it only supports three of the big five (Chrome, Safari 5+, Firefox 4+), but like mentioned previously its a technology thats in its pre-infancy (don't use it in a production environment).

Lets have a look at some code:

 
#import('dart:dom');
 
void LimitTextAreas()
{
  NodeList nodes = window.document.getElementsByTagName("textarea");  
  for (int i = 0; i < nodes.length;i++)
    {
      HTMLTextAreaElement obj = nodes[i];
      Node node = obj.attributes.getNamedItem("maxlength");
      if (node != null)
      {
        int maxlength = Math.parseInt(node.nodeValue);
        obj.addEventListener("keypress", (KeyboardEvent e) {
          if (((e.keyCode == 8) || (e.keyCode > 36) && (e.keyCode < 41)) 
              || (obj.value.length < maxlength)) return;        
            e.preventDefault();
        });
        obj.addEventListener("paste", (Event e){      
          window.setTimeout((){        
            if(obj.value.length > maxlength)
              obj.value = obj.value.substring(0, maxlength);
          }, 1);
        });
      }
    }
}
 
void main() {
  LimitTextAreas();
}
 


Looks familiar and JavaScripty right? Well, a lot of parts also feel a lot like Java/C#, you can even create proper classes etc. But hang on, is it statically typed, why did I define all the types?

No, its actually a dynamically typed language just like JavaScript, so you'll be able to replace NodeList, int, HTMLTextAreaElement etc all with the var keyword.

Statically typing your variables are completely optional, but I prefer doing it since it might help me in catching errors earlier etc, you can read more about it over here.

Otherwise it seems like a very simple/easy language to learn.

Its going to be interesting to see if/how the programming community embraces this new language within the next few years.

Concerns



But hey, wait a minute, these technologies seem awfully similar, dont they? It actually led me to ask the following question to one of the google devs I met recently:

Hi Mike

Just a quick question (if you dont mind)

How committed do you believe Google is to its GWT project ?

I am asking this in context of the following two things.

  1. its parent project only having a 15 month lifespan, from public release to being annouced discontinued.

  2. The dart project - which feels like a like minded project?


I didn't get a response from Mike, but I found a post on the official GWT blog where someone answers this question.

The GWT team is basically saying that they see Dart as an evolution of GWT's mission (evolution generally entails the extinction of the less evolved species), but don't worry guys we're (Google) using GWT as well, so we're not planning to kill it off too soon.

Here is a full discussion on the subject.

You can also download the source code for this post over here.

In the next part we're going to have a look at Mootools.







Post comment

Name *
Email
Title
Body *
Security Code
*
* Required fields

Related Posts

Latest Posts

MS SQL: Parameter Sniffing


2012-05-21 22:38:48

Be the best stalker you can be


2011-12-13 22:33:54

Top 5 posts

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21