0

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.

asked Nov 19, 2019 at 18:39

2 Answers 2

4

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);
 }
}
answered Nov 19, 2019 at 18:42
Sign up to request clarification or add additional context in comments.

2 Comments

Cheers this worked. Are there any disadvantages to using this notation? I'm new to OO Js and Js in general.
@John Nope. It's the new ES6 notation. Arrow functions don’t bind this to the object that called them. They just use the value of this in the scope in which they were defined. You can read more about it here - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

It's because of wrong binding for this

call handler function like below

window.addEventListener("click", this.onConnDragClick.bind(this));
answered Nov 19, 2019 at 18:41

1 Comment

onConnDragClick is not the function that can't be called.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.