首页 > 解决方案 > 如何取消监听 MDCDialog 事件

问题描述

我有一个听的小功能MDCDialog:closing

问题是,每次我运行这个函数时,它都会添加一个新的监听器。
所以,一旦我完成使用它,我需要删除这个相同的侦听器。

到目前为止,这就是我所做的:

function confirm() {
    mdcAlert.open();
    // start listening
    mdcAlert.listen("MDCDialog:closing", function(event) {
        {... execute what need to be done ...}

        // stop listening (not working)
        mdcAlert.unlisten("MDCDialog:closing");
    });
}

你碰巧知道怎么用unlisten吗?

我不知道如何在文档中使用它:
https ://material.io/develop/web/components/dialogs/
https://pub.dev/documentation/mdc_web/latest/mdc_web/MDCComponent/unlisten。 html

标签: material-componentsmaterial-components-web

解决方案


找到了解决方案。

必须传递一个内部带有函数的变量。

function confirm() {
    let eventListener=function(event) {
        {... execute what need to be done ...}

        //Unlisten after execution
        mdcAlert.unlisten("MDCDialog:closing", eventListener);
    };

    mdcAlert.open();
    mdcAlert.listen("MDCDialog:closing", eventListener);
}

推荐阅读