如何在 Vaadin 中添加点击监听器到自定义通知?

问题描述 投票:0回答:1

我想添加一个外部单击侦听器来检测用户何时在组件外部单击。 我创建了一个

CustomNotification.java
,当用户在 CustomNotification 实例外部单击时,我想关闭或隐藏它。 我用了好几种方法,还是不行。

public class CustomNotification extends Notification  implements ClickNotifier<Notification> {

    public CustomNotification(Component content) {
        Div contentWrapper = new Div(content);

        // Add the provided content to the dialog
        add(contentWrapper);
        
        setDuration(0); 
        setPosition(Position.BOTTOM_END); 
        
        // Add click listener
        ComponentUtil.addListener(this, ClickEvent.class, event -> {
            if (event.getSource() != null && event.getSource() != this) {
                this.close();
            }
        });
        
        addClickListener(event -> {
            if (event.getSource() != null && event.getSource() != this) {
                close();
            }
        });
        


        // Show the dialog
        open();
    }
    

    public static CustomNotification showNotification(Component content) {
        CustomNotification notification = new CustomNotification(content);              
        return notification;
    }
}

它的用法。

public void openMessageDialog()
{
     customNotification = CustomNotification.showNotification(createDialogLayout());
     
     customNotification.addClickListener(event -> {
         if (event.getSource() != null && event.getSource() != customNotification) {
             customNotification.close();
         }
     });
     
     customNotification.getElement( ).addEventListener("click", e -> {
         if (e.getSource() != null && e.getSource() != customNotification.getElement( )) {
             customNotification.close();
         }
     });
}
java vaadin-flow vaadin24
1个回答
0
投票

这应该有效。

Notification notification = new Notification("Test");
notification.getElement().executeJs(
  "document.addEventListener('click', (event) => {" +
    "if (event.target != $0._card) {" +
      "$0.close();" +
    "}})", notification.getElement());
notification.open();

感谢Serhii Kulykov的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.