D
D
DmitryLife2021-11-20 14:11:00
AJAX
DmitryLife, 2021-11-20 14:11:00

How to call object function from AJAX callback?

Good afternoon.

I created a class, in it I created a method that receives data from the server via AJAX.
After receiving the data, I want to call the class method, but if I call it via this, then it looks for a function in the callback apparently.

How to call a class function? (this.createRectangle method)

class MapClass {

  map = document.querySelector('#map')
  lands = []
  widthRec = 10
  heightRec = 10

  constructor() {
    /*Create map sheet*/
    $.get('/api/getmap', {some:'test'}, function(response){
      this.lands = response
      for (let i = -5; i <= 5; i++) {
        for (let j = -5; j <= 5; j++) {
          this.lands.forEach( function(element, index) {
            console.log(element)
          });
          this.createRectangle((i * 10),(j * 10))
        }			
      }
    })
  }

  createRectangle(x,y) {
    let rec = document.createElementNS("http://www.w3.org/2000/svg",'rect')
    rec.setAttribute('x', x)
    rec.setAttribute('y', y)
    rec.setAttribute('width', this.widthRec)
    rec.setAttribute('height', this.heightRec)
    rec.classList += ' map__box'
    this.map.appendChild(rec)
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Pautov, 2021-11-20
@DmitryLife

Replace

$.get('/api/getmap', {some:'test'}, function(response){

on the
$.get('/api/getmap', {some:'test'}, (response) => {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question