简体   繁体   中英

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. You have two options:

You could make scrollthis an object:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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