0

I have a Vue method call error, while I'm trying to call a method from inside an other method of the application:

The JS:

const app = new Vue({
el: '#info',
data() {
    return {
        position: {},
        areas: {}
    };
},
ready() {
},

mounted() {
},
methods: {
    prepareComponent(){

    },
    loadContent(){
        console.log(this.position);
        let queryString = '?lat='+this.position.coords.latitude+'&lon='+this.position.coords.longitude;
        axios.get('/api/getarea'+queryString)
            .then(response => {
                this.areas = response.data;
                this.showAreaData();
            });
    },
    showAreaData(){
        var cities = [];
        for(var area of this.areas){
            cities.push(area.city);
        }
        console.log(cities);
    },
    getLocation(){
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                this.position = position;
                this.loadContent();
            }, function(error) {
                console.log(error);
            });
        }
    },
},
});

and here is the html:

            <div id="info">
                <a href="#" id="getPosition" class="btn btn-link" @click="getLocation">Get Position</a>
                <ul>

                </ul>
            </div>

After running the code, I got an error that loadContent is not defined (TypeError: this.loadContent is not a function). What am I missing here?

2 Answers 2

2

try add var _this= this; use _this.loadContent(); or use app.loadContent();

getLocation(){
 var _this= this;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                this.position = position;
                _this.loadContent();
            }, function(error) {
                console.log(error);
            });
        }
    },
Sign up to request clarification or add additional context in comments.

1 Comment

ahhh, thanks. :) I'm too tired, maybe that's why I've missed such a basic thing.
1

this refers to the object that called a function. In the present case, this is navigator.geolocation. You can override the calling object by calling bind on the function:

getLocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            this.position = position;
            this.loadContent();
        }.bind(this), function(error) {
            console.log(error);
        });
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.