管理 Javascript Class 中的点击事件?

Manage clicks events inside Javascript Class?

我一直在使用具有 ES6 某些功能的旧香草 javascript (es5),现在我正在做一些事情,所以我创建了一个 class 来显示我的 html内容,在网页中,然后添加点击

我的 class 是:

class Field {
    constructor(key, label, status, isUnsubscribed){
        this.key = key;
        this.label = label;
        this.status = status;
        this.isUnsubscribed = isUnsubscribed;
    }

    // want this to be executed on click
    test(){
        alert(this.key);
    }

    returnHTMLField(){

        // Global Container
        let fieldContainer = document.createElement("div");
        
        fieldContainer.addEventListener("click", function(){
            // issue here, this return the element itself, which makes sense
            this.test()
        })

        return fieldContainer;
    }
}

所以基本上我正在创建一个对象,方法是将组件添加到 DOM,这在另一个 class 的帮助下工作正常,但现在每当我点击我想要测试要执行的函数,但是 eventListener 操作中的 this 没有返回 Object state,它正在返回组件(DOM 元素),这是正常行为,我不知道如何在事件侦听器中执行测试函数..

如有任何帮助,我们将不胜感激

您可以使用 arrow 函数将 this 绑定到父作用域,而不是创建单独的 lexical 作用域。

class Field {
    constructor(key, label, status, isUnsubscribed){
        this.key = key;
        this.label = label;
        this.status = status;
        this.isUnsubscribed = isUnsubscribed;
    }

    // want this to be executed on click
    test(){
        alert(this.key);
    }

    returnHTMLField(){

        // Global Container
        let fieldContainer = document.createElement("div");
        
        fieldContainer.addEventListener("click",() => {
            // issue here, this return the element itself, which makes sense
            this.test()
        })

        return fieldContainer;
    }
}

尝试使用箭头函数:

fieldContainer.addEventListener("click", ()=>{
    this.test()
})

因此,如果您更喜欢 ES5,那么 .bind(this) 就可以了。

class Field {
    constructor(opts){
        Object.assign(this, opts); // Bonus ES6 code here 
    }

    // want this to be executed on click
    test(){
        alert(this.key);
    }

    returnHTMLField(){

        // Global Container
        let fieldContainer = document.createElement("div");
        
        fieldContainer.addEventListener("click", function(){
            // issue here, this return the element itself, which makes sense
            this.test()
        }.bind(this)) // <--- HERE

        return fieldContainer;
    }
}

var f = new Field({ key           : 10
                  , label         : "Test"
                  , status        : "OK"
                  , isUnsubscribed: false
                  });
                  
console.log(f.returnHTMLField().dispatchEvent(new Event("click")));