Thursday, September 9, 2010

Re: How to use external JS from GWT?

You are having a timing problem that is common for GWT. Consider how
this would work in pure JavaScript.

1. The page loads
2. The external JavaScript files load
3. The page renders
4. Your JavaScript code is called and you make your field
alphanumeric.

With GWT the order of operations changes. This is because GWT has a
bootstrap mechanism they use to load the correct GWT files based on
your browser and language. In GWT the order looks like this:

1. The page loads
2. The external JavaScript files load
3. The page renders
4. Your JavaScript code is called
5. GWT JavaScript loads the new HTML page with your JavaScript code
6. GWT calls your onModuleLoad method
7. GWT add the HTML controls to the DOM

In your example you are trying to access DOM elements in step six, but
they aren't available until step seven. I had a similar problem when
I wanted to use the JQuery date picker on a GWT text box. The
solution is the onAttach method in
com.google.gwt.user.client.ui.Widget.

My class looks like this:

public class DatePickerTextBox extends TextBox
{
public DatePickerTextBox(String id)
{
super();
getElement().setId(id);
}

public void onAttach()
{
super.onAttach();
addDatePickerJS(getElement().getId());
}

private static native void addDatePickerJS(String id) /*-{
$wnd.$('#' + id).datepicker();
}-*/;
}

In this case I require the field to have an ID so I can use JQuery to
find it. I then wait until the attach happens because I call my
JQuery function. Now my order of operations looks like this:

6. GWT calls your onModuleLoad method
7. GWT add the HTML controls to the DOM
8. GWT calls the onAttach method and I call my JavaScript function

It is also worth noting that this pattern creates a reusable widget
that internalizes all of the JavaScript. Code using this widget has
no idea that it is using JavaScript and I could easy replace the
implementation without breaking the contract of the control.

I hope this helps,
Zack

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To post to this group, send email to google-web-toolkit@googlegroups.com.
To unsubscribe from this group, send email to google-web-toolkit+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/google-web-toolkit?hl=en.

No comments:

Post a Comment