Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Scroll event listener used in conjection with throttling function

Tags:

javascript

I have function which I call which opens a particular view on my page.

function dayViewOpen(target){
         var date = getDate();
          ..
          ..
          ..
        document.addEventListener('scroll',throttle(function(event){
            scrollAddData(date);
        },10));
}

similarly I have a function to close that particular view

 function dayViewClose(target){
        ..
        ..


    }

everything till now its working perfectly. But problems start arising when I have to remove the earlier added event listener. I.e I have to remove the event listener when i call the function dayViewclose();

I get it that we need to have a reference to listener to remove it, so I when i do it like this.

var handler = throttle(function(event){
                scrollAddData();
            },10);

 function dayViewOpen(target){
         var date = getDate();
          ..
          ..
          ..
        document.addEventListener('scroll',handler,false);
}

 function dayViewClose(target){
        ..
        ..

        //remove earlier added event listener
       document.removeEventListener('scroll',handler,false);
    }
  • then I am not able to pass the date parameter to the to my handler ( how can i pass the date parameter to the handler ) and
  • Even if i let go of the date param then also i am not able to remove the handler with removeEvent Listener. ( how can i remove the event listener properly )

Any help would be greatly apreciated

like image 972
bhavya_w Avatar asked Sep 23 '14 16:09

bhavya_w


1 Answers

You can try declaring the event listener outside, but setting it inside:

var handler;

function dayViewOpen(target){
    var date = getDate();
    /* ... */
    handler = throttle(function(event){
        scrollAddData(date);
    }, 10);
    document.addEventListener('scroll', handler, false);
}

function dayViewClose(target){
    /* ... */
    document.removeEventListener('scroll', handler, false);
}
like image 75
Oriol Avatar answered Oct 07 '22 00:10

Oriol