Forums

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

Home Forums JavaScript How to pass current object to throttled function

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

    So I’ve got this little script that listens to scroll events:

    $('.item').scroll(function() {
    
      var move = $(this).scrollTop();
    
      ...
    
    });
    

    And this function to throttle events:

    $.restrain = function(delay, callback) {
    
      var executed = 0, debounce,
      throttle = function() {
    
      var elapsed = Math.min(delay, Date.now()-executed),
      remain = delay-elapsed;
      debounce && clearTimeout(debounce);
      elapsed == delay && runIt();
      if (remain) debounce = setTimeout(runIt, remain);
    
      function runIt() {
      executed = Date.now();
      callback.apply(this, arguments);
      }
      }
      return throttle;
    }
    

    Combined, they would look thus:

    $('.item').scroll($.restrain(50, function() {
    
      var move = $(this).scrollTop();
    
      ...
    
    }));
    

    But the problem is that this now no longer refers to the element being scrolled but to window instead.

    Anyone have an idea how I can pass this to the inner function itself?

    #262320
    Shikkediel
    Participant

    Any suggestions welcome…

    For now I’ve gone with a loop (with is kinda circumventing the issue instead of solving it):

    $('.item').each(function(i) {
    
      $(this).scroll($.restrain(50, function() {
    
        var move = $('.item').eq(i).scrollTop();
    
        ...
    
      }));
    });
    
    #262324
    Shikkediel
    Participant

    Same kind of thing when passing events, which is harder to circumvent in a decent way…

    $('.item').scroll(function(e) {
    
      e.preventDefault();
    
      ...
    
    });
    
    $('.item').scroll($.restrain(50, function(e) {
    

    That e in the second snippet (naturally) won’t work when written like this.

    #262361
    Shikkediel
    Participant

    Workaround:

    $('.item').scroll(function(e) {
    
      e.preventDefault();
    
      ...
    
    })
    .scroll($.restrain(50, function() {
    
      ...
    
    }));
    

    Meh.

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