GWT Button Click Enable/Disable Pattern -- GwtEvent assertLive() in dev mode - gwt

To avoid users clicking repetitively on the same button and by the same token send multiple requests to server, I have used the following pattern:
In button ClickHandler.onClick, disable the button.
In call back, re-enable the button.
See pattern in code below. The "rpcCall" function below basically is the core implementation of the Button onClick(final ClickEvent event).
private void rpcCall(final ClickEvent event)
{
final AsyncCallback<Void> callback = new AsyncCallback<Void>()
{
#Override
public void onSuccess(Void result)
{
final Button source = (Button) event.getSource(); // Dev mode isLive assertion failure.
source.setEnabled(true);
// Process success...
}
#Override
public void onFailure(Throwable caught)
{
final Button source = (Button) event.getSource();
source.setEnabled(true);
// Process error...
}
};
// Disable sender.
final Button source = (Button) event.getSource();
source.setEnabled(false);
// RPC call.
final RpcAsync rpcAsync = getRpcAsync();
RpcAsync.rpcCall(..., callback);
}
I just noticed a "This event has already finished being processed by its original handler manager, so you can no longer access it" exception caused by an isLive assertion failure in dev mode when the onSuccess async function calls event.getSource().
It seems to work in production/javascript mode though.
This dev mode assertion failure makes me question this pattern.
Is it a good pattern? Why do I get the exception only in dev mode? What would be a better pattern?
Obviously, I could bypass the call to event.getSource() by passing the source Button as an argument of the rpc wrapper call function, but it seems redundant with the event object already carrying such a reference.

Historically, the way you got the event object in IE was to use window.event, which only lasted the time to process the event. GWT's Event object therefore had to put guards so you're discouraged to keep a hold on an event instance, as it could suddenly reflect another event being processed, or no event at all (weird!)
Fortunately, Microsoft has since fixed their browser, and this is why it works when you test it (I bet you didn't test in IE6 ;-) ).
The correct way to handle that situation is to extract all the data you need from the event and keep them in final variables:
private void rpcCall(final ClickEvent event)
{
final Button source = (Button) event.getSource();
final AsyncCallback<Void> callback = new AsyncCallback<Void>()
{
#Override
public void onSuccess(Void result)
{
source.setEnabled(true);
// Process success...
}
#Override
public void onFailure(Throwable caught)
{
source.setEnabled(true);
// Process error...
}
};
// Disable sender.
source.setEnabled(false);
// RPC call.
final RpcAsync rpcAsync = getRpcAsync();
RpcAsync.rpcCall(..., callback);
}

Related

How to call GWT client code from within a GQuery event handler?

I'm learning GQuery. It seems cool, but also a little confusing.
I have the following GWT client code. The selected item fades out, nicely. But the delete method never gets called. There is no error. It's very odd.
Is it even possible to call non-GQuery functions from inside a GQuery method?
delete.addClickHandler( new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
$(myIndicator).fadeOut(500, new Function(){
#Override
public void f() {
super.f();
delete();
}
});
}
});
And the delete method is:
private void delete() {
removeFromParent();
ruleDeleteRequestEvent.fire(new RuleDeleteRequestEvent(ruleBinder.getModel()));
}
Do not call super.f(), if so the default implementation of Function.f() will throw an Exception preventing the next line be executed (take a look to the source code) .

GWT Delaying an action after an event trigger

I want to have the user click a button, then they will see a "Toast" message popup, which fades away , then the action that the button click performs should happen. What is the best way to do this? Should I trigger a Timer on catching the click event and let it timeout (While the toast is being displayed ) and then call the handling code or is there any built in delay mechanism in event handling I can use?
I don't want my toast to be involved at all in the event handling
If I really follow your requirements the following code should do:
// interface of the "Toast" no matter what the implementation actually is
public interface Toast
{
void open( String message );
void closeFadingAway();
}
// calling code
public class ClientCode
{
private static final int myDelay = 1000; // 1 second in millis
private Toast myToast;
void onMyAction()
{
myToast.open( "Your action is being handled..." );
Scheduler.get().scheduleFixedDelay( new RepeatingCommand()
{
#Override
public boolean execute()
{
myToast.closeFadingAway();
performAction();
return false; // return false to stop the "repeating" = executed only once
}
}, myDelay );
}
void performAction()
{
// do something interesting
}
}
Now, if you actually mean to be able to interrupt the action when the user presses some button in the toast this is a different story.
If you are using a popup panel you could use the addCloseHandler on the popup panel and from here call the method that would have otherwise been called by the button.
popUpPanel.addCloseHandler(new CloseHandler<PopupPanel>(){
#Override
public void onClose(CloseEvent<PopupPanel> event) {
// TODO Do the closing stuff here
}
});
So when the PopupPanel disappears and the close event triggers you can do your magic there.

GWT is making an unexpected event call

My code is below: I am seeing that on running the app the loadWidget method gets invoked even when the adminLink is not clicked. This is not want I want, but I'm not sure what is causing the issue. Please advise
public class LoginModule implements EntryPoint {
LoginPopup loginPopup;
private class LoginPopup extends PopupPanel {
public LoginPopup() {
super(true);
}
public void loadWidget(){
System.out.println("I am called 1");
CommonUi cUi = new CommonUi();
//#342 moved code to common area
FormPanel loginForm = cUi.getLoginFormUi();
setWidget(loginForm);
}
}
#Override
public void onModuleLoad() {
//#251 improved login popup ui.
final Anchor adminLink = new Anchor("User Login");
// final Label adminLink = new Label("User Login");
adminLink.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// Instantiate the popup and show it.
loginPopup = new LoginPopup();
loginPopup.loadWidget();
loginPopup.showRelativeTo(adminLink);
loginPopup.show();
}
});
if(RootPanel.get("admin") !=null)
RootPanel.get("admin").add(adminLink);
}
}
Running Dev Mode, set a breakpoint in that method in your Java IDE, and take a look at the current stack, what code is calling that method. If that is the only code in your app, then this only appears to be invokable from that onClick handlers, so it is a matter of figuring out why that is being invoked.

Firing ListGrid selection item on GWT

When the user clicks a button, I want to fire the ListGrid Selection event. I called "resultControl.resultGrid.selectRecord(0);" but it didn't work.
From your initial question and your comment, I understand that you want to simulate a selection event in your ListGrid, through a button. Assuming that I understand well, and you are only interested in one record selection (the first one), all you have to do is the following:
final ListGrid listGrid = new ListGrid();
//Initialize your listgrid's data etc.
listGrid.addSelectionChangedHandler(new SelectionChangedHandler() {
#Override
public void onSelectionChanged(SelectionEvent event) {
SC.say("here my code");
}
});
IButton button = new IButton("Select");
button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
listGrid.selectRecord(0);
}
});
A last note, System.out or System.err won't produce anything when your application runs in production mode. Use a suitable logging solution or the SC.say(), if you want to provide the user with a message, instead.

How to intercept the onSuccess() method in GWT

I need to do method interception for the onSuccess method in GWT.
I need to add some code before and after the calling of the onSuccess method in GWT? (I have many calls to the onSuccess method and I need to do this dynamically)
EDIT:
I need to add a progress bar in the right corner of the screen, that appears when the code enters the onsuccess method and disappears on the exit of onsuccess method.
From a visual perspective
void onSuccess(Value v) {
showProgressBar();
doLotsOfWork(v);
hideProgressBar();
}
will be a no-op. Browsers typically wait for event handlers to finish executing before re-rending the DOM. If the doLotsOfWork() method takes a noticeable amount of time to execute (e.g. >100ms) the user will notice the browser hiccup due to the single-threaded nature of JavaScript execution.
Instead, consider using an incrementally-scheduled command to break the work up. It would look roughly like:
void onSuccess(Value v) {
showProgressBar();
Scheduler.get().scheduleIncremental(new RepeatingCommand() {
int count = 0;
int size = v.getElements().size();
public boolean execute() {
if (count == size) {
hideProgressBar();
return false;
}
processOneElement(v.getElements().get(count++));
setProgressBar((double) count / size);
return true;
}
});
}
By breaking the work across multiple pumps of the browser's event loop, you avoid the situation where the webapp becomes non-responsive if there's a non-trivial amount of work to do.
Well, it is a generic non-functional requirement, I have done some research on this item, I have implemented a solution that Thomas Broyer has suggested on gwt group.. This solution has distinct advantage over other suggested solutions, You dont have to change your callback classes, what you have to do is just add a line of code after creation of async gwt-rpc service...
IGwtPersistenceEngineRPCAsync persistenceEngine = GWT.create(IGwtPersistenceEngineRPC.class);
((ServiceDefTarget) persistenceEngine).setRpcRequestBuilder(new ProgressRequestBuilder());
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.rpc.RpcRequestBuilder;
public class ProgressRequestBuilder extends RpcRequestBuilder {
private class RequestCallbackWrapper implements RequestCallback {
private RequestCallback callback;
RequestCallbackWrapper(RequestCallback aCallback) {
this.callback = aCallback;
}
#Override
public void onResponseReceived(Request request, Response response) {
Log.debug("onResposenReceived is called");
// put the code to hide your progress bar
callback.onResponseReceived(request, response);
}
#Override
public void onError(Request request, Throwable exception) {
Log.error("onError is called",new Exception(exception));
// put the code to hide your progress bar
callback.onError(request, exception);
}
}
#Override
protected RequestBuilder doCreate(String serviceEntryPoint) {
RequestBuilder rb = super.doCreate(serviceEntryPoint);
// put the code to show your progress bar
return rb;
}
#Override
protected void doFinish(RequestBuilder rb) {
super.doFinish(rb);
rb.setCallback(new RequestCallbackWrapper(rb.getCallback()));
}
}
You cant do that. The rpc onSuccess() method runs asynchronously (in other words, depends on the server when it completes, the app doesnt wait for it). You could fire code immediately after the rpc call which may/ may not complete before the onSuccess for RPC calls.
Can you explain with an eg why exactly do u want to do that? Chances are you might have to redesign the app due to this async behavior, but cant say till you provide a use case. Preferably any Async functionality should be forgotten after the rpc call, and actioned upon only in the onSuccess.