Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Function scope for event listener removal

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #288776
    Shikkediel
    Participant

    This does not remove the event listener:

    function test() {
    
      window.removeEventListener('wheel', log);
      window.addEventListener('wheel', log);
    
    function log() {
      $('#log').append('hello world<br>');
    }
    }
    

    codepen.io/zQevWy

    This however does:

    function test() {
    
      window.removeEventListener('wheel', log);
      window.addEventListener('wheel', log);
    }
    
    function log() {
      $('#log').append('hello world<br>');
    }
    

    codepen.io/PvVEXa

    Is there any way to make the function be seen as identical without removing it from the parent function’s scope? In my actual test case, hoisting raising [or insert more applicable technical term] it messes with variable scope too much…

    #288778
    Shikkediel
    Participant

    Okay, one could keep an external reference of the function in an array outside the scope.

    A bit meh but it works…

    var listen = [], pair = [];
    
    function test() {
    
      var spot = listen.indexOf(window);
    
      window.removeEventListener('wheel', pair[spot]);
      window.addEventListener('wheel', log);
    
      listen.splice(spot, 1);
      pair.splice(spot, 1);
      listen.push(window);
      pair.push(log);
    
    function log() {
      $('#log').append('hello world<br>');
    }
    }
    

    codepen.io/XwOPrG

    Now that I think about it… I’ve been messing with data objects lately so I might as well store the function reference there. But better suggestions are welcome.

    #288925
    Shikkediel
    Participant

    This is roughly what I ended up with, where args represents the data object attached to the element:

    var args = {};
    
    function test() {
    
      var now = ['wheel', log, {passive: false}];
    
      if (args.now) window.removeEventListener.apply(this, args.now);
      window.addEventListener.apply(this, now);
    
      args.now = now;
    
    function log() {
      $('#log').append('hello world<br>');
    }
    }
    

    codepen.io/joReqQ

    It seemed to make more sense to pass the entire set of arguments at once.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.