简体   繁体   中英

How to call same function from different places using different parameters in javascript and still retain old values of variables of that function?

I have following code in my geolocation program.

When user allows device to get the geolocation, the geolocation() function gets called and the geolocation function again propagates the successPosition function with position object that gives latitude and longitude. Inside the successPosition function I also need other variable called btype (Blood type) since I am developing a program to find nearest blood doners.

So in the past I tried to ask user which blood type to search using javascript prompt method but using that approach user would have to manually type the blood type but what I want is to let user select the type from dropdown. But If I create a form and ask user the type and pass object to SuccessPosition function, the position object becomes undefined - this is because this time we are only passing btype and we dont have position . And when position object gets passed the another variable btype is undefined.

Please tell me what is the best approach to solve the problem.

geolocation: function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(this.successPosition, this.failurePosition, {
      enableHighAccuracy: true,
      timeout: 3000,
      maximumAge: 4000
    });

  } else {
    return (false);
  }
},
successPosition: function(position) {
  self.latitude = position.coords.latitude;
  self.longitude = position.coords.longitude;

  //self.btype = btype;

  self.partial_url = ("/users?utf8=✓&longitude=" + (self.longitude) 
                   + "&latitude=" + (self.latitude)
                   + "&btype=" + encodeURIComponent(self.btype));

  window.location = self.partial_url;

}

Your successPosition function doesn't have to be responsible for setting the window.location immediately. I think the simplest thing in your case would be to have successPosition trigger the form which allows the user to select their blood type, and have an event listener bound to the form element which calls something like setWindowLocation with the blood type when the user selects one. Now you'll have your geolocation and your blood type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM