繁体   English   中英

变量作为eventListener命名的函数表达式名称

[英]Variable as eventListener named function expression name

我正在写一个很棒的IIFE,希望对使用它的用户来说尽可能简单。 所以我在想,因为其中有些人不知道要在没有事件监听器的情况下轻松删除它,我们可以给该内联函数命名

document.addEventListener('click',function dood(){
    //some function
},false);
document.removeEventListener('click',dood,false);
//instead of 
function dood(){
  //some function
} 
document.addEventListener('click',dood,false);
document.removeEventListener('click',dood,false);

但是因为他们不应该确切知道这个名字,所以我想知道我们是否可以

var k = "name_of_function";
document.addEventListener('click',function window[k](){
  //the function
},false);

虽然我知道这行不通,但是有办法吗? 我想做到这一点,以便他们可以轻松地做到这一点

object.cancel('name_of_function') //which will be the name of the instance
// they created earlier if they gave that instance a name
object={
  cancel:function(nm){
    document.removeEventListener(self.trigger,window[nm],false);
    //self.trigger really is this.trigger which they assign as either scroll,click,mousemove,etc.
  }
};

有任何想法吗? 还是根本不可能?

用法是:

scrollex('element',{
    max:500,
    min:500,
    pin:200,
    offset:0.5,
    name:'google',//this then would be used in multiple instances
});

scrollex.events //shows all events and their names
scrollex.listen('google'); //it'll console log all info for this event
scrollex.cancel('google');

我认为您在正确的轨道上。 但是,您不应使用window和某些本地对象。 动态命名函数表达式(或function window[k](){}应该具有的含义)是不可能 的事 -不要尝试这样做。 只是让它们保持匿名,并仅通过属性名称/变量来引用它们。

var object = (function() {
    var listeners = {
        name_of_function: function dood(){…}
    };
    document.addEventListener('click', listeners.name_of_function, false);

    return {
        cancel: function(nm) {
            document.removeEventListener('click', listeners[nm], false);
        }
    };
}());

// now, you can
object.cancel('name_of_function')

暂无
暂无

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

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