0

How would I remove the event listener set in this JavaScript function? I'd like to do it from another function if possible? If that's not possible then from within the same function would work.

function _dtmCheckFundingEditLink() {


    function _dtmGetCurrentFundingAmount() {

        var currAmt = "NA";

        try {

            currAmt = sessionStorage.getItem("_dtmFundAmount");

        } catch (err) {

            return currAmt;

        }

        return currAmt;

    };



    editLink = document.querySelectorAll('.btn-grp-back');



    if (editLink != null) {

        editLink[2].addEventListener('click', function() {

            var clNm = s.pageName + ":" + _dtmGetCurrentFundingAmount() + ":edit";

            _dtmReportCL(clNm);

        })

    } else {

        setTimeout(_dtmCheckFundingEditLink, 1000);

    }

};
Michael Johns
  • 419
  • 3
  • 21
  • 1
    Possible duplicate of [Javascript removeEventListener not working](https://stackoverflow.com/questions/10444077/javascript-removeeventlistener-not-working) – yqlim Jul 26 '19 at 04:01

1 Answers1

1

Declare your function that gets called by the event listener as a separate function and not as an anonymous function:

function handler(){
  //handle event
}

add the event listener:

.
.
.
if (editLink != null) {

        editLink[2].addEventListener('click', handler);

    } else {

        setTimeout(_dtmCheckFundingEditLink, 1000);

    }
.
.
.

and now you can remove that handler from a separate function:

 function sampleFunction(){
   editLink = document.querySelectorAll('.btn-grp-back');
   editLink[2].removeEventListener('click', handler); 

}
SP de Wit
  • 215
  • 1
  • 9