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

February 7, 2012 by Christoff Truter JavaScript   Cross Browser  

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.

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


Related Downloads

Set maximum length of a textbox


Leave a Comment



Related Posts

Solving Cross Browser Issues - Part 3 (Mootools and HTML5)

February 23, 2012

Solving Cross Browser Issues - Part 1 (JQuery and GWT)

January 9, 2012


Latest Posts

Enhance Customer Registration Process with Cutting-Edge Solutions from Card Scanning Solutions Inc.

November 4, 2013

JavaScript Threading - Part 2 (Worker)

December 18, 2012

JavaScript Threading - Part 1 (Timers)

December 18, 2012

MS SQL: Parameter Sniffing

May 21, 2012

Solving Cross Browser Issues - Part 3 (Mootools and HTML5)

February 23, 2012

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

February 7, 2012

Solving Cross Browser Issues - Part 1 (JQuery and GWT)

January 9, 2012

Be the best stalker you can be

December 13, 2011

AjaxControlToolkit (ASP.NET/C#) : CascadingDropDown Extender - Part 2

November 3, 2011

AjaxControlToolkit (ASP.NET/C#) : CascadingDropDown Extender - Part 1

October 7, 2011


Most Commented on Posts

Moving items between listboxes in ASP.net/PHP example

Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
June 12, 2008

Simple WYSIWYG Editor

Creating a WYSIWYG textbox for your website is actually quite simple.
February 1, 2007

C# YouTube : Google API

Post on how to integrate with YouTube using the Google Data API
March 12, 2011

Populate a TreeView Control C#

Populate a TreeView control in a windows application.
August 27, 2009

Cross Browser Issues: Firefox Word Wrapping

Firefox word wrapping issues
June 9, 2008


ASP.NET   C#   C++   Comedy   Cross Browser   Design Patterns   IIS   Integration   JavaScript   Microsoft Office   Personal   PHP   SQL   Threading   Visual Basic   XML