RAP Client Scripting Phase II (2/3)
June 6, 2013 | 2 min ReadPart 2: How to Pass Data to Your ClientListener
A ClientListener is executed in a completely different environment to a traditional SWT listener. The only data it has access to is the event object, which in turn has a reference to the ClientScripting-version of the widget that fired the event. Until now, the almost only way to pass any data to a ClientListener was to hard-code it into the JavaScript. Consider this code for a Verify listener:
function handleEvent( event ) {
var regexp = new RegExp( "^[0-9]*$" );
if( !regexp.test( event.text ) ) {
event.doit = false;
}
}
The user is only allowed to enter numbers in a text field. If we wanted to allow, let’s say, only lower case letters or any other regular expressions, a completely new ClientListener with a different script would be required. This can not only become cumbersome (since the JavaScript has to be either hardcoded as a string literal or read from an external source), but can result in an unnecessary amount of ClientListener instances (see also yesterday’s post).
With RAP 2.1 there is a much better option. You may be familiar with the widget.setData(key, value)
and widget.getData(key)
methods that allow you to attach any object to a widget instance. While the ClientScripting (JavaScript) widgets objects also have these methods, the data itself was until now in no way shared between server and client. Now it is possible.
To do this we need to use the new WidgetDataWhiteList
class found within the ClientScripting bundle. The class allows us to define which keys of any widgets data-map will be synchronized to the client. For example:
WidgetDataWhiteList.addKey( "myProject.myRegExp" );
// valid for all widgets in this session:
oneWidget.setData( "myProject.myRegExp", "^[0-9]*$" );
anotherWidget.setData( "myProject.myRegExp", "^[a-z]*$" );
And the new ClientListener code:
function handleEvent( event ) {
var widget = event.widget;
var regexp = new RegExp( widget.getData( "myProject.myRegExp" ) );
if( !regexp.test( event.text ) ) {
event.doit = false;
}
}
See a list of supported value types. Note that the data is currently only synchronized in one direction: Changing the value on the server also changes it on the client, but not vice-versa.
Tomorrow
… I will tell you how this feature can be used for cross-widget scripting.