是否可以在 GWT 中向父 DivElement 实例添加或删除子元素时触发事件?
Is it possible to fire event on addition or removal of child element to parent DivElement instance in GWT?
我有一个内容可编辑的 GWT DivElement 实例,我正在向其动态附加一些元素。我可以在每次向父 DivElement 实例添加子元素时触发事件吗?
您可以使用 MutationObserver 来做您需要的事情。
您在 DivElement 上设置了一个 Observer 并观察 childList
变化。在 MutationRecord
你可以得到 addedNodes
列表。
MutationObserver 没有原生 GWT 支持,因此您需要使用 JSNI:
private native void addListener(Element elem) /*-{
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.type == 'childList') {
// mutation.addedNodes contains nodeList of added nodes
$wnd.alert('Nodes added');
}
});
});
// configuration of the observer:
var config = {
childList : true
};
// pass in the target node, as well as the observer options
observer.observe(elem, config);
}-*/;
只需在您的 DivElement 上调用 addListener(div);
。
我有一个内容可编辑的 GWT DivElement 实例,我正在向其动态附加一些元素。我可以在每次向父 DivElement 实例添加子元素时触发事件吗?
您可以使用 MutationObserver 来做您需要的事情。
您在 DivElement 上设置了一个 Observer 并观察 childList
变化。在 MutationRecord
你可以得到 addedNodes
列表。
MutationObserver 没有原生 GWT 支持,因此您需要使用 JSNI:
private native void addListener(Element elem) /*-{
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.type == 'childList') {
// mutation.addedNodes contains nodeList of added nodes
$wnd.alert('Nodes added');
}
});
});
// configuration of the observer:
var config = {
childList : true
};
// pass in the target node, as well as the observer options
observer.observe(elem, config);
}-*/;
只需在您的 DivElement 上调用 addListener(div);
。