Momo
Momo

Reputation: 2491

ChangeValueHandler not fired when clicking on the back button In GWT

I have a form and I want to display a confirmation dialogBox when the user presses the back button. Let say that I have one Texbonx that listens to a ChangeValueHandler

addValueChangeHandler(new ValueChangeHandler<String>() {    
    @Override
    public void onValueChange(ValueChangeEvent<String> event) {
        setChanged(true);
    }
}); 

This is the short scenario

1) I enter text in the TextBox

2) I hit the back button

3) The ValueChangeEvent is not called

I tried the fire the BlurEvent programmatically on the TextBox with textBox.fireEvent(new BlurEvent() { }); but still no result.

Any suggestions ?

Upvotes: 1

Views: 268

Answers (2)

Momo
Momo

Reputation: 2491

What I did is to set the focus of the TextBox to False and then check if it's changed, that forces the TextBox to unfocus when hiting the back button.

This is the code that check if a form is changed

public boolean isChanged(){
    if(formPanel == null) return false;     
    for (int i = 0; i < formPanel.getWidgetCount(); i++) {
        if(formPanel.getWidget(i) instanceof BaseWidget){
            BaseWidget w= (BaseWidget) formPanel.getWidget(i);
            w.setFocus(false);
            if(w.isChanged()){
                return true;
            }
        }
    }
    return false;
}

Upvotes: 0

Strelok
Strelok

Reputation: 51481

When the page is closed (by pressing the back button, or closing the page) no events will be fired by the controls. What will fire first is window.onbeforeunload to give you a chance to warn the user about data loss and offer to stay on the page. If the user chooses to stay on the page, then all the events that were supposed to be fired, will fire (so your change event will fire).

You can attach a handler to the native onbeforeunload event by using Window.addClosingHandler.

Window.addWindowClosingHandler(new ClosingHandler() {

        @Override
        public void onWindowClosing( ClosingEvent event )
        {
            event.setMessage("If you leave the page now all data will be lost.");
        }

});

It's worth noting that the ClosingEvent and it's underlying onbeforeunload event, cannot, under any circumstances, be cancelled programmatically. The only way to prevent the user from leaving the page is if the user itself chooses "Stay On This Page" in the popup that results from the code above.

Upvotes: 1

Related Questions