How to removeEventListener that was added using closure?

后端 未结 1 1330
遇见更好的自我
遇见更好的自我 2021-01-17 16:13

This is basically a followup question to this: Can't pass event to addEventListener: closure issue.

I have read almost every related question and can\'t find the

1条回答
  •  攒了一身酷
    2021-01-17 17:08

    You have to keep references to your listeners:

    var listeners = {};
    for(/* ... */) {
       (function outerfunction(i, f) {
            var listener = function(e) { 
                responsefunction(e, f, i); 
            }
            elementname.addEventListener("click", listener);
            listeners[elementname.id] = listener; // use something meaningful 
                                                  // as your keys
       })(parameter1, parameter2);
    }
    
    // Removing the listener later:
    elementname.removeEventListener("click", listeners[elementname.id]);
    

    0 讨论(0)
提交回复
热议问题