使用ES6类与jQuery配合

3

我刚刚在我的新项目中遇到了一个小问题。基本上,有一个帖子页面和一些作为页面一部分从后端传来的评论。我想要做的就是为这些评论提供一些JavaScript逻辑。我所做的就是提供:

class Comment {
    constructor(comment) {
        console.log("Creating comment object...");
        $(comment).find(".vote").click(this.toggle_vote);
        $(comment).find(".action.reply").click(this.toggle_reply);
    }

    toggle_vote() {
        // Context here is `span.reply`, not Comment instance,
        // but I want to access class members
        if ($(this).is(".voted")) {
            $(this).removeClass("voted");
            return;
        }

        $(this).addClass("voted");
        $(this).siblings().first().removeClass("voted");
    }

    // ...
}

以下问题涉及jQuery的回调函数。当我将类成员传递给jQuery回调时,在调用过程中,jQuery模拟了其上下文,因此thisspan.reply,而不是Comment实例。重点是我希望能够访问实际的Comment实例。
声明:我完全不懂前端,因此可能需要一些严格的解释来解决这个问题,谢谢!

这与使用ES6类语法无关。 - Bergi
顺便说一下,你的 toggle_vote 函数似乎期望 this 是 DOM 元素? - Bergi
@Bergi,目前它确实可以,但我希望它能以另一种方式运行。我听说 ES6 中有一个“=>"语法,它在这里能用吗? - Ian P Badtrousers
是的,你可以使用 ….click((e) => this.toggleReply(e.currentTarget)) 或类似的方式。 - Bergi
1个回答

1

我可以用 ES6 的 "=>" 语法绑定它吗,像这样:.click((event) => this.toggle_vote) - Ian P Badtrousers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接