I'm having a hard time to remove Event listener type currying function.
// I register first, at some time I want to remove using freezeHighlight but it doesn't working (without currying function it's working like a charm)
const privateMethods = {
highlighted (index) {
return function (event) {
event.target.setAttribute('filter', 'url(#glow)')
// need param index later
}
}
}
register (node, index) {
node.addEventListener('mouseover', privateMethods.highlighted(index))
}
freezeHighlight (node) {
node.removeEventListener('mouseover', privateMethods.highlighted)
}
Is it possible to remove event listener type currying function or should I procede with a workaround?
You need to memoize the handler you create so that you can remove it later.
const handlers = {};
const privateMethods = {
highlighted (index) {
// return the saved handler if we've been called before
// or create a new handler, save it, and return it.
return handlers[index] || (handlers[index] = function (event) {
event.target.setAttribute('filter', 'url(#glow)')
// need param index later
});
}
}
register (node, index) {
// add the handler
node.addEventListener('mouseover', privateMethods.highlighted(index))
}
freezeHighlight (node, index) {
// will remove the handler
node.removeEventListener('mouseover', privateMethods.highlighted(index))
}
var listener
register (node, index) {
listener = privateMethods.highlighted(index)
node.addEventListener('mouseover', )
}
freezeHighlight (node) {
node.removeEventListener('mouseover', listener)
}
You think privateMethods.highlighted
is the listener. No it's not. The return value of privateMethods.highlighted(index)
is the listener.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.