【问题标题】:I cannot make an event listener inside object constructor to listen我无法在对象构造函数中创建事件监听器来监听
【发布时间】:2019-06-09 14:27:41
【问题描述】:

当我滚动 div 时,基本上没有任何反应。 slideIt 方法在对象启动时被触发一次,就是这样。它不听滚动事件!为什么会发生这种情况?

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
      }); 

}

【问题讨论】:

  • 表达式this.scrollable_div.scroll(this.slideIt()) 调用该函数。您需要传递对函数的绑定引用:this.scrollable_div.scroll(this.slideIt.bind(this))
  • @Pointy 成功了。请把它作为答案,以便我批准。

标签: javascript jquery javascript-objects


【解决方案1】:

一个常见的 JavaScript 错误是键入函数 call,而需要的是对函数的引用(通常用于设置事件处理程序,但也有其他类似的情况)。 p>

这样

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

调用this.slideIt() 函数并将返回值传递给.scroll 方法,这显然不是我们想要的。 this.slideIt 之后的 () 是造成这种情况的原因,所以 this.slideIt 没有 () 是必要的。

现在,完成后,下一个问题将是与this 的关系将丢失。 There are various questions on Stackoverflow with long, thorough answers about how this works. 在这里只想说,需要确保正确设置 this

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

(还有其他方法可以做到这一点,但应该可以。)

【讨论】:

    猜你喜欢
    • 2012-09-25
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2014-02-21
    • 2010-12-30
    • 1970-01-01
    相关资源
    最近更新 更多