Javascript ES6 里面的addEventListener Class

Javascript ES6 addEventListener inside Class

我正在学习 ES6,我不明白为什么当我使用这样的函数时我的 addEventListener 不工作(只触发一次):

// Trigger only one time
window.addEventListener("scroll", this.scroll() );

但是当我这样做的时候:

// working !!
window.addEventListener("scroll", (e) => {
    let top = window.pageYOffset;

    console.log(top + " vs " + this.offsetTop)

    if (top >= this.offsetTop) {
        this.el.classList.add('is-sticky');
    } else {
        this.el.classList.remove('is-sticky');
    }

});

完整的代码可以在这里找到:https://codepen.io/paallaire/pen/GQLzmg/?editors=0010#0

声明:

window.addEventListener("scroll", this.scroll() );

this.scroll() 的结果绑定到事件,这是一个函数调用。这样调用returnsundefined,因为scroll方法没有return语句:

scroll() {
    let top = window.pageYOffset;
    console.log(top + " vs " + this.offsetTop);

    if (top >= this.offsetTop) {
        this.el.classList.add('is-sticky');
    } else {
        this.el.classList.remove('is-sticky');
    }
}

正确的方法

不要使用:

window.addEventListener("scroll", this.scroll);

上面的代码会在事件触发时将 this 绑定到 window

正确的使用方法是:

window.addEventListener("scroll", (e) => {
   this.scroll();
});

window.addEventListener("scroll", this.scroll.bind(this));

其中,当事件被触发时,this.scroll 中的代码会将 this 指向当前 class (Sticky) 实例。


正在删除事件侦听器

要删除事件,请调用 window.removeEventListener,但有一个警告:必须使用与 addEventListener 中使用的完全相同的参数调用 removeEventListener 以删除侦听器。换句话说,要删除您必须执行的操作:

// save the function that will be bound to the event, so you can remove it later
this.scrollBoundFunction = this.scroll.bind(this);
window.addEventListener("scroll", this.scrollBoundFunction);

// and later
window.removeEventListener("scroll", this.scrollBoundFunction);