matekm
matekm

Reputation: 6030

Class and attribute problem

I wanted to play with geolocation API on my Android. I know that there is a "navigator" object that is defined and that should be used to aquire user position. So, I created this sample code:

function GeolocationTester()
{
    // here I want to store all acquired locations
    this.locations = new Array();
    alert("this.locations defined: " + this.locations);
    this.onSuccess = function(position)
    {
        alert("Entered onSuccess");
        alert("this.locations defined: " + this.locations);
    }

    this.onError = function(error)
    {
        alert("error acquiring location");
    }
    navigator.geolocation.watchPosition(this.onSuccess, this.onError, { enableHighAccuracy: true });
}

And it doesn't work for me. Each time watchPosition call onSuccess the this.locations field isn't defined (and it is defined just after new Array). I known that I'm doing somethind wrong, but as it is one of my JavaScript attempts, not sure what. So, anybody could find a problem here?

Upvotes: 1

Views: 72

Answers (3)

Igor Dymov
Igor Dymov

Reputation: 16460

Try to define onSuccess like this:

this.onSuccess = (function(locations) {
    return function(position)
           {
               alert("Entered onSuccess");
               alert("this.locations defined: " + locations);
           }
})(this.locations);

Upvotes: 0

Andreas Köberle
Andreas Köberle

Reputation: 110932

Its cause you using this. This will change cause its depends on the context your function is calling on. Just use the scope of the function to declare location:

function GeolocationTester()
{
    // here I want to store all acquired locations
    var locations = [];
    alert("locations defined: " + locations);

    function onSuccess(position)    {
        alert("Entered onSuccess");
        alert("locations defined: " + locations);
    }

   function onError(error){
        alert("error acquiring location");
   }


 navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
}

To really understand what this read this blog post http://dmitrysoshnikov.com/ecmascript/chapter-3-this/

Upvotes: 2

dm3
dm3

Reputation: 2058

The problem is with the scoping of this. When the onSuccess or onError is called, this isn't bound to the object containing the locations array. You need to create an explicit variable outside of the functions to which the array should be assigned and then use this variable in the callbacks, like this:

var allLocations = this.locations = [a, b, c];
this.onSuccess = function(position) {
    alert("allLocations: " + allLocations);
    alert("this.locations: " + this.locations);
}

Upvotes: 3

Related Questions