Answer the question
In order to leave comments, you need to log in
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
Replace
$.get('/api/getmap', {some:'test'}, function(response){
$.get('/api/getmap', {some:'test'}, (response) => {
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question