简体   繁体   English

如何为可与 removeEventListener 一起使用的 addEventListener 创建包装函数?

[英]How can I create a wrapper function for addEventListener that works with removeEventListener?

I want to create a wrapper function for addEventListener that I can call as such:我想为addEventListener创建一个包装函数,我可以这样调用:

aEvt('click', document, function (evt, target) {
  //Code here
});

I want to do this because it allows me to always have the event target available first from the start as a parameter.我想这样做是因为它允许我始终将事件目标作为参数从一开始就可用。
I attempted such a function, but the problem is, in order to have it work with removeEventListener (or my analogous rEvt function), I have to return a callback from the aEvt function and pass that to removeEventListener as the callback.我尝试了这样一个函数,但问题是,为了让它与removeEventListener (或我的类似rEvt函数)一起工作,我必须从aEvt函数返回一个回调并将其传递给removeEventListener作为回调。

The aEvt function I currently have is as follows:我目前拥有的aEvt函数如下:

function aEvt(evt, elem, fn) {
  'use strict';

  var callback = function (evt) {
    fn(evt, evt && evt.target ? evt.target : window.event.srcElement);
  };

  if (elem.addEventListener) {
    elem.addEventListener(evt, callback);
  } else if (elem.attachEvent) {
    elem.attachEvent('on' + evt, callback);
  } else {
    elem['on' + evt] = callback;
  }

  return callback;
}

Is there any way I can change the aEvt function so that I can send the target to the callback passed to the aEvt function (ie, fn ), but also have the callback I send to the aEvt function be the same callback that I send to the analogous rEvt function I want to write?有什么方法可以更改aEvt函数,以便我可以将目标发送到传递给aEvt函数的回调(即fn ),但也可以让我发送到aEvt函数的回调与我发送到的回调相同我想写的类似的rEvt函数?
In other words, how should I change aEvt to make the following work?换句话说,我应该如何更改aEvt以进行以下工作?

var callbackFn = function (evt, target) { console.log(target); };
aEvt('click', document, callbackFn);
rEvt('click', document, callbackFn);

Felix Kling, thanks a lot for your answer in the SO post you linked to in the comments. Felix Kling,非常感谢您在评论中链接的 SO 帖子中的回答。

I took what you did and modified it slightly to 1) follow the JS code standards set at my organization, and 2) make it so that I could get the event target as a parameter in the handler callback.我采用了您所做的并将其稍微修改为 1) 遵循在我的组织中设置的 JS 代码标准,以及 2) 使其能够将事件目标作为处理程序回调中的参数获取。
Having the target available as a parameter makes handling events a lot easier in a majority of the use cases I have as well as greatly minimizes the amount of refactoring required.将目标作为参数可以在我拥有的大多数用例中更轻松地处理事件,并且大大减少了所需的重构量。

Anyway, here's the final code (please note that the each function in remove executes a simple for loop, and return false in the function essentially breaks the loop):无论如何,这是最终的代码(请注意, remove中的each函数执行一个简单的 for 循环,并且函数中的return false基本上打破了循环):

var evts = (function () {
  'use strict';

  var listeners = [],
    add,
    remove;

  add = function (evt, elem, fn) {
    var callback = function (evt) {
      fn(evt, evt && evt.target ? evt.target : window.event.srcElement);
    };

    listeners.push({
      evt: evt,
      elem: elem,
      fn: fn,
      callback: callback,
      removed: false
    });

    if (elem.addEventListener) {
      elem.addEventListener(evt, callback);
    } else if (elem.attachEvent) {
      elem.attachEvent('on' + evt, callback);
    } else {
      elem['on' + evt] = callback;
    }
  };

  remove = function (evt, elem, fn) {
    var callback;

    each(listeners, function (evtObj) {
      if (evtObj.evt === evt && evtObj.elem === elem && 
          evtObj.fn === fn && !evtObj.removed) {
        evtObj.removed = true;
        callback = evtObj.callback;
        return false;
      }
    });

    if (elem.removeEventListener) {
      elem.removeEventListener(evt, callback);
    } else if (elem.detachEvent) {
      elem.detachEvent('on' + evt, callback);
    } else {
      elem['on' + evt] = null;
    }
  };

  return {
    add: add,
    remove: remove
  };
}());

And here's an example of using the methods:这是使用这些方法的示例:

var callback = function (evt, target) {
  console.log(target);
};
evts.add('click', document, callback);
evts.remove('click', document, callback);

暂无
暂无

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

相关问题 如何使用匿名函数删除作为addEventListener的EventListener? - How to removeEventListener that is addEventListener with anonymous function? 带有部分功能的Javascript addEventListener和removeEventListener - Javascript addEventListener and removeEventListener with partial function 需要参数的addEventListener(和removeEventListener)函数 - addEventListener (and removeEventListener) function that need param 如何在JavaScript中的方法中的addEventListener和全局函数中的removeEventListener时调用removeEventLisener - How to call removeEventLisener when addEventListener in a method and removeEventListener in a global function in JavaScript 如何使用removeEventListener禁用addEventListener? - How to use removeEventListener to disable addEventListener? 如何在类中的(作用域)addEventListener上应用removeEventListener? - How do I apply removeEventListener on an (scoped) addEventListener in a class? 使用removeEventListener删除包装函数回调 - Removing a wrapper function callback with removeEventListener removeEventListener 不工作(函数不是匿名的,和 addEventListener 完全一样!!) - removeEventListener is not working (function is not anonymous, exactly the same as addEventListener!!) 使用addEventListener javascript添加后,removeEventListener()不会删除函数 - removeEventListener() not removing function after added with addEventListener javascript 添加addEventListener后似乎无法删除eventListener - Can't seem to removeEventListener after adding addEventListener
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM