Austin
Austin

Reputation: 345

Calling method from another method in the same class

Right now I am trying to call a method from another method within the same class. When I try to do this I get the error

this.beginConnDrag is not a function

Here is what the class looks like with just the methods of importance shown.

    class NEditor {
    constructor() {
        ...
    }

    ...

    beginConnDrag(path) {
        if (this.dragMode != 0) return;

        this.dragMode = 2;
        this.dragItem = path;
        this.startPos = path.output.getPos();

        this.setCurveColor(path.path, false);
        window.addEventListener("click", this.onConnDragClick);
        window.addEventListener("mousemove", this.onConnDragMouseMove);
    }

    onOutputClick(e) {
        e.stopPropagation();
        e.preventDefault();
        var path = e.target.parentNode.ref.addPath();
        console.log(e.target.parentNode);
        console.log("output clicked");

        this.beginConnDrag(path);
    }
}

This error is being thrown on the bottom line of the onOutputClick() method when it tries to call the beginConnDrag component. If these are not static methods I don't understand why this call is not allowed.

Upvotes: 0

Views: 163

Answers (2)

Shivratna Kumar
Shivratna Kumar

Reputation: 1311

You can use arrow functions to keep your this object unchanged:-

class NEditor {
    constructor() {
        ...
    }

    ...

    beginConnDrag = (path) => {
        if (this.dragMode != 0) return;

        this.dragMode = 2;
        this.dragItem = path;
        this.startPos = path.output.getPos();

        this.setCurveColor(path.path, false);
        window.addEventListener("click", this.onConnDragClick);
        window.addEventListener("mousemove", this.onConnDragMouseMove);
    }

    onOutputClick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        var path = e.target.parentNode.ref.addPath();
        console.log(e.target.parentNode);
        console.log("output clicked");

        this.beginConnDrag(path);
    }
}

Upvotes: 4

Loken Makwana
Loken Makwana

Reputation: 3848

It's because of wrong binding for this

call handler function like below

window.addEventListener("click", this.onConnDragClick.bind(this));

Upvotes: 1

Related Questions