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.
2 Answers 2
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);
}
}
2 Comments
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/… It's because of wrong binding for this
call handler function like below
window.addEventListener("click", this.onConnDragClick.bind(this));