Handle DIV add child node event with GWT

668 views Asked by At

Is there such a thing in GWT to handle event when elements are added to a specific DIV?

From this answer there is jQuery solution:

Fire jQuery event on div change

$('body').on('DOMNodeInserted', '#common-parent', function(e) {
  if ($(e.target).attr('class') === 'myClass') {
    console.log('hit');
  }
});
1

There are 1 answers

0
shyyko.serhiy On BEST ANSWER

You can integrate jquery method by using jsni.

At first you need to create corresponding gwt like event:

package com.test.gwt;

import com.google.gwt.event.shared.GwtEvent;

public class DOMNodeInsertedEvent extends GwtEvent<DOMNodeInsertedEventHandler> {
    public static Type<DOMNodeInsertedEventHandler> TYPE = new Type<DOMNodeInsertedEventHandler>();

    public Type<DOMNodeInsertedEventHandler> getAssociatedType() {
        return TYPE;
    }

    protected void dispatch(DOMNodeInsertedEventHandler handler) {
        handler.onDOMNodeInserted(this);
    }
}

and gwt like handler:

package com.test.gwt;

import com.google.gwt.event.shared.EventHandler;

public interface DOMNodeInsertedEventHandler extends EventHandler {
    void onDOMNodeInserted(DOMNodeInsertedEvent event);
}

then implement jsni wrapping function

public native void addDOMNodeInsertedEventHandler(Widget widget, Element element)/*-{
    $wnd.$(element).bind('DOMNodeInserted', function (event) {
        var gwtEvent = @com.test.gwt.DOMNodeInsertedEvent::new()();
        [email protected]::fireEvent(Lcom/google/gwt/event/shared/GwtEvent;)(gwtEvent);
    });
}-*/;

and at last add your handler to corresponding panel

FlowPanel flowPanel = new FlowPanel();
flowPanel.addHandler(new DOMNodeInsertedEventHandler() {
    @Override
    public void onDOMNodeInserted(DOMNodeInsertedEvent event) {
        Window.alert("Inserted");
    }
}, DOMNodeInsertedEvent.TYPE);
addDOMNodeInsertedEventHandler(flowPanel, flowPanel.getElement());