我有一个带有构造函数体的自定义小部件,像这样
public MyWidget() {
this.containerDiv = DOM.createDiv();
this.containerDiv.getStyle().setPosition(Position.ABSOLUTE);
this.containerDiv.getStyle().setLeft(20, Style.Unit.PX);
this.containerDiv.getStyle().setTop(20, Style.Unit.PX);
this.containerDiv.getStyle().setWidth(50, Style.Unit.PX);
this.containerDiv.getStyle().setHeight(20, Style.Unit.PX);
final Element canvasContainer = DOM.createDiv();
canvasContainer.getStyle().setPosition(Position.ABSOLUTE);
canvasContainer.getStyle().setLeft(0, Style.Unit.PX);
canvasContainer.getStyle().setTop(0, Style.Unit.PX);
canvasContainer.getStyle().setBottom(0, Style.Unit.PX);
canvasContainer.getStyle().setRight(20, Style.Unit.PX);
this.canvas = DOM.createCanvas();
this.canvas.getStyle().setWidth(100, Unit.PCT);
this.canvas.getStyle().setHeight(100, Unit.PCT);
canvasContainer.appendChild(this.canvas);
this.containerDiv.appendChild(canvasContainer);
setElement(this.containerDiv);
DOM.sinkEvents((Element) this.canvas.cast(), Event.ONCLICK);
DOM.setEventListener((Element) this.canvas.cast(), new EventListener() {
@Override
public void onBrowserEvent(final Event event) {
Window.alert("canvas click");
}
});
DOM.sinkEvents((Element) canvasContainer.cast(), Event.ONCLICK);
DOM.setEventListener(canvasContainer, new EventListener() {
@Override
public void onBrowserEvent(final Event event) {
Window.alert("Bubble click");
}
});
DOM.sinkEvents((Element) this.containerDiv.cast(), Event.ONCLICK);
DOM.setEventListener(this.containerDiv, new EventListener() {
@Override
public void onBrowserEvent(final Event event) {
Window.alert("Container click");
}
});
}
生成如下HTML
<div style="position: absolute; left: 20px; top: 20px; width: 50px; height: 20px; ">
<div style="position: absolute; left: 0px; top: 0px; bottom: 0px; right: 20px; ">
<canvas style="width: 100%; height: 100%; "/>
</div>
</div>
当我点击画布时,我得到两个警报"画布点击"one_answers"气泡点击",但没有"容器点击"。
为什么?
当您添加小部件时,将调用其onAttach()
方法。如果您检查此方法的源代码,您将注意到它将浏览器事件的事件侦听器重新定义为DOM.setEventListener(getElement(), this)
的小部件。根据该函数的javadoc,一个元素只能存在一个这样的侦听器。由于您的containerDiv是由控件的getElement()
返回的,因此您为元素定义的onBrowserEvent将被控件的默认onBrowserEvent实现所取代。这就是为什么Window.alert()
从来不被称为