如何删除已作为匿名函数传入的事件侦听器?

时间:2016-12-20 19:05:10

标签: javascript events

在向对象添加事件侦听器时,我必须将参数传递给我的函数,因此必须像el.addEventListener("click", (evt) => { someFunc(arg) })那样包装它。但是,我无法在我的项目中删除此事件侦听器。当被引用的函数是匿名函数时,如何删除事件侦听器?

2 个答案:

答案 0 :(得分:2)

使用removeEventListener要求您保留对函数的引用。

var func = (evt) => { someFunc(arg) };
el.addEventListener("click", func);
el.removeEventListener("click", func)

答案 1 :(得分:1)

您可以使用removeEventListener创建String ^ ToManagedString(const char * pString) { return Marshal::PtrToStringAnsi(IntPtr((char *)pString)); // Marshal pString into Managed Memory. return as a C# string reference (^). } const std::string ToStdString(String ^ strString) { IntPtr ptrString = IntPtr::Zero; std::string strStdString; try { ptrString = Marshal::StringToHGlobalAnsi(strString); // Marshal a C# String reference into unmanaged HEAP memory space. strStdString = (char *)ptrString.ToPointer(); // Convert C# IntPtr to char* implicitly, call assignment operator of std::string to copy. } finally { if (ptrString != IntPtr::Zero) { Marshal::FreeHGlobal(ptrString); } } return strStdString; // return std::string copied out of interop unmanaged heap space } 功能,以便稍后在整个项目中使用多种类型的事件:

addOneTimeEventListener

而不是使用它:

function addOneTimeEventListener(node, type, callback) {
    node.addEventListener(type, function(evt) {
        evt.target.removeEventListener(evt.type, arguments.callee);
        return callback(evt);
    });
}

工作演示:



addOneTimeEventListener(el, 'click', evt => someFunc(arg));

var addOneTimeEventListener = function(node, type, callback) {
      node.addEventListener(type, function(evt) {
        evt.target.removeEventListener(evt.type, arguments.callee);
        return callback(evt);
      });
    },
    el = document.getElementById('paragraph');

addOneTimeEventListener(el, 'click', evt => console.log('Clicked once!'));