| J2JS | |
| Home > Docs > Tutorial 3 | |
|
Tutorial 1 Tutorial 2 Tutorial 3 This tutorial will present a simple DHTML table widget. The table will allow operations such as insertion, data loading from server and deletes. It will make use of AJAX features through the XMLHttpRequest object. The code is contained in the j2js-Demos project, and is available online as a demo. 1. Java Code
The core class is the
Next, write a facade through which the user agent interacts with the table. This facade will only contain
static methods. We already learned how to register event handlers. This will happen in the /** * Attach click-event handlers to buttons. */ public static void onLoad() { EventListener listener = new EventListener() { public void handleEvent(Event evt) { HTMLElement target = (HTMLElement) evt.getTarget(); String id = target.getId(); if (id.equals("create")) create(); else if (id.equals("addRow")) addRow(); else if (id.equals("fetch")) fetch(); else if (id.equals("removeSelection")) removeSelection(); else if (id.equals("clear")) clear(); else throw new RuntimeException("Illegal action: " + id); } }; String[] ids = new String[] {"create", "fetch", "addRow", "removeSelection", "clear"}; for (int i=0; i<ids.length; i++) { Element elem = Global.document.getElementById(ids[i]); ((EventTarget) elem).addEventListener("click", listener, false); } } Extracted from /projects/j2js-Demos/src/java/j2js/demo/table/TableDemo.java
In the /** * Creates the table with headers. */ public static void create() { if (table != null) { throw new RuntimeException("Table already created"); }
The table is attached at /** * Fetches some rows from the server. */ public static void fetch() { checkCreated(); HttpRequest request; String method; HTMLSelectElement select = (HTMLSelectElement) Global.document.getElementById("HttpRequestType"); if (select.getSelectedIndex() == 0) { request = XMLHttpRequest.getSingleton(); method = "POST"; } else if (select.getSelectedIndex() == 1) { request = FormHttpRequest.getSingleton(); method = "POST"; } else { request = ScriptHttpRequest.getSingleton(); method = "GET"; } request.open(method, "fetchTable.php", true); request.setReadyStateChangeListener(table); request.send(null); } Extracted from /projects/j2js-Demos/src/java/j2js/demo/table/TableDemo.java
Note that the table was registered as the listener for 2. HTML CodeThe HTML-code must contain the referenced buttons <button id="create" title="Create a table">Create</button>
<button id="fetch" title="Fetch some rows from the server">Fetch</button>
Extracted from /projects/j2js-Demos/src/site/table/TableDemo.html
and the div-element:
<div id="MyDiv"></div> Extracted from /projects/j2js-Demos/src/site/table/TableDemo.html | |
| Last build on Sat Jan 03 11:06:48 CET 2009 | |