简体   繁体   English

如何使用currying函数删除事件侦听器

[英]How to remove Event listener with currying function

I'm having a hard time to remove Event listener type currying function. 我很难删除事件侦听器类型的currying函数。

// 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? 是否可以删除事件侦听器类型的currying函数,还是应该继续解决?

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. 您认为privateMethods.highlighted是侦听器。 No it's not. 不,这不对。 The return value of privateMethods.highlighted(index) is the listener. privateMethods.highlighted(index)的返回值是侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM