简体   繁体   English

的JavaScript-AddEventListener到本地范围内的函数?

[英]JavaScript - AddEventListener to a function in a local scope?

I have a set of functions that need global variables, and in an effort to not pollute the global namespace, I've been trying to find a way to localize them. 我有一组需要全局变量的函数,并且为了不污染全局名称空间,我一直在尝试寻找一种本地化它们的方法。 However, I also want to trigger them from the outside with an event listener. 但是,我也想通过事件监听器从外部触发它们。 I would prefer not to use an anonymous function in the event listener on the off chance that one day I want to remove that event listener. 如果有一天我想删除该事件监听器,我不希望在事件监听器中不使用匿名函数。

(I've not been able to learn if event listeners with anonymous functions auto destroy the same way the functions themselves do, or if they stay in the page until reloaded.) (我无法了解具有匿名函数的事件侦听器是否会自动破坏函数本身的方式,或者它们是否留在页面中直到重新加载。)

This is what I have (which doesn't work). 这就是我所拥有的(不起作用)。

I want this to work: 我想要这个工作:

window.onload = function() {
  document.addEventListener('mousewheel', scrollthis.scrolldown, false);
}

var scrollthis() {
  function scrolldown() {
    // code that does stuff
  }
  return  {
    scrolldown:scrolldown
  }
}

Any ideas? 有任何想法吗?

Right now scrollthis is a function, and you're trying to use it like an object. 现在, scrollthis是一个函数,您正在尝试像对象一样使用它。 You have two options: 您有两种选择:

You could make scrollthis an object: 您可以将scrollthis对象:

window.onload = function() {
  document.addEventListener('mousewheel', scrollthis.scrolldown, false);
}

var scrollthis = {
  scrolldown: function () {
    // code that does stuff
  }
}

Or you could call the scrollthis function before trying to access the scrolldown fucntion: 或者你可以拨打scrollthis试图访问之前功能scrolldown温控功能:

window.onload = function() {
  document.addEventListener('mousewheel', scrollthis().scrolldown, false);
}

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

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