Search code examples
material-componentsmaterial-components-web

How to unlisten MDCDialog event


I have a small function which listen to MDCDialog:closing.

The problem is, each time I run this function, it add a new listener.
So, I need to remove this same listener once I'm done using it.

So far, this is what I did:

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");
    });
}

Do you happen to know how to use unlisten?

I can't figure out how to use it in the doc:
https://material.io/develop/web/components/dialogs/
https://pub.dev/documentation/mdc_web/latest/mdc_web/MDCComponent/unlisten.html


Solution

  • Found the solution.

    Had to pass a variable with a function inside.

    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);
    }