1

i want to add event handler to object's class (with JQUERY), but i cannot find solution to my problem. I have code like this:

class Obstacle
{
    constructor()
    {
        this.points = [];
    }
}

class Editor
{
    constructor()
    {
        this.obstacle = new Obstacle;
    }

    addPoint()
    {
        this.obstacle.points.push(canvas.click( function(e) { return [e.clientX, e.clientY]; }));  
        alert(this.obstacle.points.length);
    }
}

Of course without any results, so i'm asking for any help :).

2
  • The return value of the event handler is never received anywhere, since the function you pass to click method, as an argument, is called from the event queue (or in this particular case, inside jQuery). What is pushed to the array is the return value of .click call, and that's done only once, when you've called addPoint(). You've to push the coordinates to the array inside the event handler function. Commented Jul 22, 2020 at 18:39
  • and, how it should be done? Actually i think that was my first idea, i tried to make that: canvas.click(function(e) { this.obstacle.points.push([e.clientX, e.clientY])}), but error occured that push method was not defined Commented Jul 22, 2020 at 18:52

1 Answer 1

1

You've to push the coordinates inside the event handler. In the current code there's no receiver to the return value from the event.

Because this in the click handler refers to the element the event is attached, you need a separate reference to this. A simple way is to store this value to a variable in the outer scope and use that to refer the actual object. Like this:

addPoint() {
  const that = this;
  canvas.click(function(e) {
    that.obstacle.points.push([e.clientX, e.clientY]);
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.