Tengo un addEventListener que usa una función curry para poder usar los parámetros de la función.
const curryFunction = (product) => { return function curry(e) { //do stuff here } } const addEvent = (product) => { document.getElementById('button').addEventListener('click', curryFunction(product)) }pero quiero poder eliminarlo, busqué preguntas similares a esta en el desbordamiento de la pila, pero como no tenían este caso específico, no parecían funcionar. Lo intenté
document.getElementById('button').removeEventListener('click', curryFunction(product)) // just didn't do anything document.getElementById('button').removeEventListener('click', curryFunction()) // gave me error document.getElementById('button').removeEventListener('click', curry()) // gave me errorjunto con las similitudes tales como
document.getElementById('button').removeEventListener('click', curryFunction) document.getElementById('button').removeEventListener('click', curryFunction(product))//this one was nested inside a function so I wouldn't get an error || product had the same value as the product in the addEvent(product) document.getElementById('button').removeEventListener('click', curry) document.getElementById('button').removeEventListener('click', curry(e))//this one was nested inside a function so I wouldn't get an error with the ey ninguno de ellos funcionó, entonces, ¿cuáles son las formas de hacerlo?
.bind() porque eso tampoco funcionóEl problema es que removeEventListener requiere una referencia al mismo "objeto" exacto, porque usará la identidad del objeto para ver qué oyente eliminar.
La función curryFunction crea una nueva instancia cada vez que se llama, por lo que debe realizar un seguimiento de esa función para eliminarla más adelante:
var myListener = undefined; const addEvent = (product) => { // Store the reference to the listener somewhere myListener = curryFunction(product); document.getElementById('button').addEventListener('click', myListener) } // later on use myListener to remove the listener document.getElementById('button').removeEventListener('click', myListener) Tenga en cuenta que, en este caso, si addEvent se llama dos veces sin llamar a removeEventListener en el medio, perderá la referencia. Entonces, debe verificar, antes de agregar un nuevo oyente, que aún no tiene uno en su lugar / eliminar el existente o puede usar una matriz / objeto para realizar un seguimiento de múltiples oyentes al mismo tiempo.