我发布第二个答案,因为现在我知道您无法更改将 DIV 添加到父级的方式。
经过一番搜索,我找到了Mutation events。它们允许您收听DOMNodeInserted 事件:
JS:
myDiv.addEventListener("DOMNodeInserted", function (ev) {
alert('added');
}, false);
在GWT中你需要使用JSNI方法:
private native void addListener(Element elem) /*-{
elem.addEventListener("DOMNodeInserted", function (ev) {
$wnd.alert('added');
}, false);
}-*/;
它有效,但是......它已被弃用。你应该改用MutationObserver。
不幸的是 MutationObserver 没有要观察的 NodeInserted 事件。我认为subtree 突变观察可以完成这项工作,但它对我不起作用。解决方案是观察父节点上的childList 突变:
JS:
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.type);
});
});
// configuration of the observer:
var config = {
childList: true
};
// pass in the target node, as well as the observer options
observer.observe(elem, config);
同样,对于 GWT,您需要将其包装在 JSNI 方法中(您知道如何)。
观察者回调中的mutation参数是一个MutationRecord对象。
所以,如果你能得到父节点,请在其上使用 MutationObserver 并观察 childList 突变。如果没有,请尝试使用已弃用的 Mutation 事件。
我知道这不是纯粹的 GWT 解决方案,但您可以使用 GWT 方法来处理事件或突变。你只需要像这样从 JSNI 调用 GWT 方法:
[instance-expr.]@class-name::method-name(param-signature)(arguments)
您可以在GWT documentation 中找到所有 JSNI 信息。