Handle DIV使用GWT添加子节点事件

时间:2013-09-07 09:57:36

标签: java javascript jquery gwt gwtquery

当元素添加到特定DIV时,GWT中是否存在处理事件的事情?

从这个答案中可以看出jQuery解决方案:

Fire jQuery event on div change

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

1 个答案:

答案 0 :(得分:0)

您可以使用jsni集成jquery方法。

首先,您需要创建相应的gwt,如事件:

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

和gwt之类的处理程序:

package com.test.gwt;

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

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

然后实现jsni包装功能

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);
    });
}-*/;

最后将您的处理程序添加到相应的面板

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