简体   繁体   中英

Handle DIV add child node event with GWT

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');
  }
});

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()();
        widget.@com.google.gwt.user.client.ui.Widget::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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM