0

I have two functions within a javascript class and I am trying to call one from inside the other, but it is not working. Why is that?

class Grid {

  paintGrid() {
    $("td").on("click", function() {
        var color = $("#colorPicker").val();
        $(this).css( "background-color", color);
    })
  }

  makeGrid() {
    $("#sizePicker").one("submit", function(e) {
        let height = $("#inputHeight").val();
        let width = $("#inputWeight").val();
        var vertical;
        for (var i = 1; i <= height; i++) {
            var vertical = document.createElement("tr");
            for (var j = 1; j <= width; j++) {
                var horizontal = document.createElement("td");
                vertical.append(horizontal);
                $("#pixelCanvas").append(vertical);
            }
        };
        e.preventDefault();
        this.paintGrid();
    })
  }
}

let creation = new Grid();
creation.makeGrid();

The thing is: when I replace this.paintGrid() for the function inside it, it works. So the error is on how I call it, I believe.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
  • `this` in the callback refers to `#sizePicker`, not to an instance of the class. – Teemu Jun 28 '18 at 16:29
  • 1
    That's not the issue. Test this code and it works: `class Grid { paintGrid() { console.log('paintGrid called'); } makeGrid() { console.log('makeGrid'); this.paintGrid(); } } const grid = new Grid(); grid.makeGrid();` .... So it is not the way the function is being called. What @Teemu sayes makes sense. – lealceldeiro Jun 28 '18 at 16:30
  • You are defining vertical twice. – cela Jun 28 '18 at 16:32
  • @Teemu, yes. The callback definitely is a key aspect here. – lealceldeiro Jun 28 '18 at 16:33

1 Answers1

1

There 2 solutions for you:

  1. Assign this to a variable

    makeGrid() {
       var self = this;
       $("#sizePicker").one("submit", function(e) {
          //...
          self.paintGrid();
       })
    }
    
  2. Using arrow function

    makeGrid() {
       $("#sizePicker").one("submit", (e) => {
          //...
          this.paintGrid();
       })
    }
    

In javascript function bind this to the caller. Arrow function binds this to current context - the class instance in this case.

You can take a look at Function vs Arrow for more information

Quy Tang
  • 3,929
  • 1
  • 31
  • 45