0

It says this.draw is not defined but I have defined draw in the same class. Why can't I call a class function inside another class function?

function Recorder() {
  this.recording = false;
  this.sideLength = 5;
  this.currList = new SLinkedList(comparator);
  this.curr = null;
}

Recorder.prototype = {
  constructor:Recorder,

  draw : function (xPos, yPos) {

    if(recording) {
      currList.addEnd([xPos,yPos]);
    }

    let context = document.getElementById("canvas").getContext("2d");
    let getColorPickerByID = document.getElementById("colors");
    let getValueOfColorPicker = getColorPickerByID.options[getColorPickerByID.selectedIndex].text;
    context.fillStyle = getValueOfColorPicker;
    context.fillRect(xPos,yPos,sideLength,sideLength); 
  },

  processMousePosition : function (evt){
    this.draw(evt.pageX, evt.pageY);
  }

};
  • How is `processMousePosition` called? – Jack Apr 05 '19 at 01:05
  • 2
    Based on `evt` as argument you are probably passing `processMousePosition` as reference to an event listener which gives it a different calling context and `this` is an element. Show how it is used – charlietfl Apr 05 '19 at 01:06

1 Answers1

1

Give your class a method named handleEvent. Make this function check the evt.type and call the appropriate method for that event.

function Recorder() {
  this.recording = false;
  this.sideLength = 5;
  this.currList = new SLinkedList(comparator);
  this.curr = null;
}

Recorder.prototype = {
  constructor:Recorder,

  handleEvent : function(evt) {
    switch (evt.type) {
      case "mousemove":
        this.processMousePosition(evt);
        break;
    }
  },

  draw : function (xPos, yPos) {
     // your draw code
  },

  processMousePosition : function (evt){
    this.draw(evt.pageX, evt.pageY);
  }
};

Then when you go to add the listener to the element, pass your instance of Recorder instead of its methods. This will cause the handleEvent method to be invoked when the event occurs.

var r = new Recorder();
myElement.addEventListener("mousemove", r);
ziggy wiggy
  • 939
  • 3
  • 5
  • @charlietfl: The value of `this` in the `handleEvent` method will be the instance of `Recorder`. – ziggy wiggy Apr 05 '19 at 01:13
  • @charlietfl: Here's a demo: https://jsfiddle.net/sr5kn1cy/ – ziggy wiggy Apr 05 '19 at 01:18
  • My bad. Admit I leaned something new. Never new about the EventListener.handleEvent before. Just looked it up in docs...interesting – charlietfl Apr 05 '19 at 01:20
  • @charlietfl: Yep, it's really handy. Creates a nice connection between the DOM elements that have associated logic, and the logic itself. It's the one thing that can bring some actual structure and organization to a web application. – ziggy wiggy Apr 05 '19 at 01:24
  • Right and don't even need to look up what method to pass to what listener – charlietfl Apr 05 '19 at 01:31