0

I have many ItemWidget which extends a Composite. If a click event is received on one of the items a change event should be fired and other item widgets should receive this event.

It tried the following:

public class ItemWidget extends Composite implements HasChangeHandlers {

   FocusPanel focusPanel = new FocusPanel();

   public ItemWidget() {

       Label label = new Label("click me");
       focusPanel.add(label);
       initWidget(focusPanel);

            focusPanel.addClickHandler(new ClickHandler() {

                @Override
                public void onClick(ClickEvent event) {
                    // inform other items
                    fireChange();

                }
            });

            addChangeHandler(new ChangeHandler() {

                @Override
                public void onChange(ChangeEvent event) {
                    GWT.log("ChangeEvent received");
                }
            });
   }

    private void fireChange() {
        GWT.log("fire event");
        NativeEvent nativeEvent = Document.get().createChangeEvent();
        ChangeEvent.fireNativeEvent(nativeEvent, this);
    }


    @Override
    public HandlerRegistration addChangeHandler(ChangeHandler handler) {
        return addDomHandler(handler, ChangeEvent.getType());
    }

}

Using the above code only the item which is clicked receives the ChangeEvent.

How can I receive the ChangeEvent on all the other item widgets too?

Michael
  • 32,527
  • 49
  • 210
  • 370
  • You want each copy of this widget to fire a change event when any one of them is clicked? It may be easier to add just one handler to a widget that contains all of them. – Andrei Volgin Feb 04 '14 at 15:17
  • @AndreiVolgin I want each widget to receive the change event. Could you post an example please? – Michael Feb 04 '14 at 15:29

2 Answers2

2

Typically, when an event fires, a presenter/Activity makes the necessary changes to the other widgets.

If you want multiple copies of you widget to listen to the same event, you may be better off using the EventBus, especially if you use this pattern more than once:

How to use the GWT EventBus

Then each of your ItemWidget can fire a custom event that all copies of this widget listen to.

Community
  • 1
  • 1
Andrei Volgin
  • 40,755
  • 6
  • 49
  • 58
0

By looking at the API quickly I think your problem comes from your implementation of

public void fireEvent(GwtEvent<?> event)

You did not override it in your composite view. You did not create any mechanism to send the event to the other widgets.

Have a deeper look at the method fireNativeEvent http://www.gwtproject.org/javadoc/latest/com/google/gwt/event/dom/client/DomEvent.html

When you use ChangeEvent.fireNativeEvent the second param hasHandlers should be a kind of event bus.

To do what you want to do I think you need all the items to be on this eventBus.

Ronan Quillevere
  • 3,699
  • 1
  • 29
  • 44