3

I just faced a little problem with my new project. Basically, there is a post page and some comments coming from back-end as part of page. All I want to do is to provide some JavaScript logic for these. What I've done is provided:

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

    // ...
}

The problem below lies in jQuery callback style. When I pass class member to jQuery callback, on the call, jQuery mocks its context, so this is span.reply, not Comment instance. The point is I want to be able to reach actual Comment instance.

Disclaimer: I am not front-end guy at all, so I might need some rigid explanation to solution of this problem, thanks!

1 Answers1

1

You can define the this-object for a function using .bind

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

In your case

.click(this.toggle_vote.bind(this))
Johannes Reuter
  • 3,501
  • 19
  • 20