-1

I am using VueJS with GoogleMaps to perform actions on a map. Therefore I wrote this function setup:

 methods: {

       // Init GIS
      init: function() {
         initGISMap(this.$els.map);
      },

       updateGIS: function() {
           getAutoCompletePlace(function(place){
               searchMarker.setPosition(place.geometry.location);
               autocompletePlace = place;

               if (place.geometry.viewport) {
                   map.fitBounds(place.geometry.viewport);
               } else {
                   map.setCenter(place.geometry.location);
                   map.setZoom(17);
               }

               self.updateIncidentForm();
           });
       },

      updateIncidentForm: function() {
          console.log("UpdateIncidentForm");
          getAddressComponents(function(components) {
              this.autoCompleteAddress = components;
              this.setIncidentAddressFields(components);
          });
      },
(...)

I want to call the updateIncidentForm function, when the getAutocompletePlace performs. The error I get in my console is:

bundle.js:11073 Uncaught TypeError: self.updateIncidentForm is not a function

Which is strange, as it is a function as defined in the code? Do I need to call the function differently?

sesc360
  • 3,155
  • 10
  • 44
  • 86

1 Answers1

3

You are calling self.updateIncidentForm() in your callback function, but you don't actually define the variable self anywhere.

Presumably, you meant to write something like:

updateGIS: function() {
    var self = this;                       // <--- you forgot this line!
    getAutoCompletePlace(function(place){
        // (irrelevant code omitted)

        self.updateIncidentForm();
    });
},

The line var self = this saves a reference to the object you called the updateGIS() method on into the local variable self, so that you can use it inside the anonymous callback function you pass to getAutoCompletePlace() (where the value of this will be something different).


BTW, in modern (ES5.1+) JavaScript, another way to achieve the same result would be to use bind() to fix the value of this inside your callback, like this:

updateGIS: function() {
    getAutoCompletePlace(function(place){
        // (irrelevant code omitted)

        this.updateIncidentForm();
    }.bind(this));
},

The .bind(this) at the end of the callback function definition locks the value of this inside the callback to the value it had in the outer updateGIS() function.

Community
  • 1
  • 1
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153