在Class里面的Javascript ES6 addEventListener

问题描述 投票:1回答:1

我正在学习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

javascript javascript-events ecmascript-6 es6-class
1个回答
4
投票

该声明:

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

将事件与this.scroll()的结果绑定,这是一个函数调用。这样的调用返回undefined,因为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');
    }
}

Correct way

不使用:

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

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

CORRECT的使用方法是:

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

要么

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

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


Removing the event listener

要删除事件,请调用window.removeEventListener,但有一点需要注意:必须使用removeEventListener中使用的完全相同的参数调用addEventListener来删除侦听器。换句话说,为了能够删除你将不得不做:

// 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);
© www.soinside.com 2019 - 2024. All rights reserved.