How to get from the Event object the object on which this event was?

I am developing a GWT application with UIBinder and I have a problem. My user interface can have many of the same elements (e.g. widgets). All elements must have handlers that catch the mouse click event. I want to write a universal handler that can identify the widget that raised the event and handle it. Now I have a widget for each object to describe the same handler. How can I solve this problem?

+4
source share
2 answers

You must pass the source object to the expected object. The getSource () method provides you only an object, but you cannot access any information from it (for example, using a button, you first need to click it on the button).

Here is an example:

Button bt = new Button("click"); bt.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Object soruce = event.getSource(); if (soruce instanceof Button) { //check that the source is really a button String buttonText = ((Button) soruce).getText(); //cast the source to a button RootPanel.get().add(new Label(buttonText)); } else { RootPanel.get().add(new Label("Not a Button, can't be...")); } } }); RootPanel.get().add(bt); 

This, of course, also works for UiBinder buttons:

 @UiHandler("button") void onClick(ClickEvent e) { Object soruce = e.getSource(); if(soruce instanceof Button){ String buttonText = ((Button)soruce).getText(); RootPanel.get().add(new Label(buttonText)); } else { RootPanel.get().add(new Label("The event is not bound to a button")); } } 

If you do not know the type of your element or the event is tied to several elements, you must first check all possible types, and then perform the correct action.

+7
source

If you want one method to handle click events for a bunch of widgets, then this is simple:

 @UiHandler({ "firstWidget", "secondWidget", "thirdWidget", "fourthWidget", andSoOn" }) void universalClickHandler(ClickEvent event) { // here, you can use event.getSource() to get a reference to the actual widget // that the event targeted. } 

If you want to use delegation delegation over a bunch of items, you need to listen for the click events on the ancestor, and then you can use event.getNativeEvent().getEventTarget() to get the actual item that was the click object. Then you can use isOrHasChild on the Element to find out if the actual click target is inside this element (e.g. firstElement.isOrHasChild(Element.as(event.getNativeEvent().getEventtarget())) , with firstElement being @UiField Element or any subclass or Element ), such as DivElement )

+1
source

Source: https://habr.com/ru/post/1402923/


All Articles