Search code examples
javascriptjqueryjavascript-objects

I cannot make an event listener inside object constructor to listen


When I scroll the div, basically nothing happens. The method slideIt gets fired once when the object is initiated and that is it. It is not listening to the scrolling event! any reason why would this happen?

function fixed_column_or_row(container_name){
    this.container_div=$(container_name);

    this.scrollable_div=this.container_div.find(".simplebar-content-wrapper");
    this.fixed_row=this.container_div.find(".fixed-row")
    this.fixed_column=this.container_div.find(".fixed-column")

    //the issue in this line
    this.scrollable_div.scroll(this.slideIt())

}

fixed_column_or_row.prototype.slideIt=function(){
     var scrollTop      = this.scrollable_div.scrollTop(),
     scrollLeft      = this.scrollable_div.scrollLeft();
     console.log("scrollTop")
     this.fixed_row.css({
         "margin-left": -scrollLeft
     });

     this.fixed_column.css({
         "margin-top": -scrollTop
      }); 

}

Solution

  • A common JavaScript mistake is to type in a function call when what's wanted is a reference to a function (for setting up an event handler, usually, but there are other similar cases).

    Thus

      this.scrollable_div.scroll(this.slideIt());
    

    will call the this.slideIt() function and pass the return value to the .scroll method, and that is clearly not what is desired. The () after this.slideIt is what causes that, so this.slideIt without () is necessary.

    Now, with that done, the next problem will be that the relationship to this will be lost. There are various questions on Stackoverflow with long, thorough answers about how this works. Suffice to say here that what's necessary is to ensure that this is correctly set:

      this.scrollable_div.scroll(this.slideIt.bind(this));
    

    (There are other ways of doing it, but that should work.)