@jeffreyvr What is 'this'? It seems like you want to access 'this' inside a callback function.
Sep 6, 2022
4
Level 1
Call method from function within mounted hook
Beginner question here :-) I'm trying to call a method from this function which is in my mounted hook.
I keep getting the error loadDetails is not a function. I found on the internet that it has something to do with the 'this'. But I can't find any solution so far. Can anybody show me the right direction?
Methods:
loadDetails() {
console.log('test')
}
Mounted:
this.map.on('click', function (e) {
console.log(transform(e.coordinate, 'EPSG:3857', 'EPSG:4326'));
var feature = this.forEachFeatureAtPixel(e.pixel, function (feature) {
return feature;
});
if (feature) {
console.log(feature.get('id'))
this.loadDetails()
}
})
Level 102
The this inside those functions are no longer the same as the original this. It's about scope
https://www.w3schools.com/js/js_scope.asp
Try this
const self = this;
this.map.on('click', function (e) {
console.log(transform(e.coordinate, 'EPSG:3857', 'EPSG:4326'));
var feature = this.forEachFeatureAtPixel(e.pixel, function (feature) {
return feature;
});
if (feature) {
console.log(feature.get('id'))
self.loadDetails()
}
})
Please or to participate in this conversation.