Search code examples
gwtwidgetcustom-componentuibindersuggestbox

How to fire a onSelection event from the custom widget to the uibinder


I created a custom SuggestBox using uibinder and I use it in the view that uses uibinder.

My problem is couldnt fire the onSelection event to the view where I am using the custom suggestbox

Below is my code.

MySuggestBox.ui.xml

<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>

</ui:style>
<g:SuggestBox ui:field="suggestionBox"></g:SuggestBox>
</ui:UiBinder> 

MySuggestBox.java

public class MySuggestBox extends Composite implements IsWidget, HasSelectionHandlers<Suggestion>{

    private static mySuggestBoxUiBinder uiBinder = GWT
        .create(mySuggestBoxUiBinder.class);

    interface MySuggestBoxUiBinder extends
        UiBinder<Widget, MySuggestBox> {
    }

   @UiField SuggestBox suggestionBox;
   public mySuggestBox(){
       initWidget(uiBinder.createAndBindUi(this));
   }

   @Override
   public HandlerRegistration addSelectionHandler(SelectionHandler<Suggestion> handler)  {
      return addHandler(handler, SelectionEvent.getType());
   }
    ...
    ...
    ...

}

and I am using the above widget here

MySuggestBoxExample.ui.xml

<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui
    xmlns:my="urn:import:com.myproject.mywidget">
<ui:style>

</ui:style>
<my:MySuggestBox ui:field="suggestBox" />
</ui:UiBinder> 

MySuggestBoxExample.java

public class MySuggestBoxExample extends Composite implements IsWidget{

    private static mySuggestBoxExampleUiBinder uiBinder = GWT
        .create(mySuggestBoxExampleUiBinder.class);

    interface MySuggestBoxExampleUiBinder extends
        UiBinder<Widget, MySuggestBoxExample> {
    }

   @UiField MySuggestBox suggestBox;
   public MySuggestBoxExample (){
       initWidget(uiBinder.createAndBindUi(this));
   }

   @UiHandler("suggestBox")
   public void onSelection(SelectionEvent<Suggestion> event){
      //I DONT GET THIS EXECUTED
   }
    ...
    ...
    ...

}

I don't get the onSelecion method triggered.

Please help.


Solution

  • Your MySuggestBox doesn't add the SelectionHandler to the actual SuggestBox, but to the Composite it extends. When the SuggestBox triggers it won't find the handlers added in you suggestion box. You can fix it by adding the handler in your MySuggestBox to the actual suggestionbox field:

    @Override
    public HandlerRegistration addSelectionHandler(SelectionHandler<Suggestion> handler)  {
      return suggestionBox.addSelectionHandler(handler);
    }