Bob Wassermann
Bob Wassermann

Reputation: 369

Use a callback in a JavaScript class

Currently I'm working on a website with an OOP, class-based, JavaScript structure. Beneath is how I implemented the Google Maps API:

class MapView extends Module {
  constructor(element, $) {
    super();
    this.$element = $(element);
    this.initMap();
  }

  initMap() {
    if ( !$('#gmaps-api').length ) {
      var api = 'AIzaSyAfPMecz3Pl6eh5zysrdqbPuyoVImSCYTg';
      var s = document.createElement('script');
      s.src = '//maps.googleapis.com/maps/api/js?key=' + api + '&callback=renderMap';
      s.type = 'text/javascript';
      s.id = 'gmaps-api';
      document.getElementsByTagName("head")[0].appendChild(s);
    }
  }

  renderMap() {
    console.log('called back');
  }
}

There are a few callbacks I already tried; like MapView.renderMap or just renderMap. How would I able to call the renderMap() function that's inside the MapView class, so I can execute some calls that render Google Maps on my page?

Upvotes: 3

Views: 1348

Answers (1)

dfsq
dfsq

Reputation: 193301

Callback function that is going to be invoked by maps script once it's available, must be a global function. That's why you can't specify MapView instance method using callback GET parameter.

What you can however do is to create global reference to necessary method. Something like this should work:

window.renderMap = this.renderMap.bind(this);

Here is complete snippet:

class MapView extends Module {
  constructor(element, $) {
    super();
    this.$element = $(element);
    this.initMap();
  }

  initMap() {
    if (!$('#gmaps-api').length) {

      window.renderMap = this.renderMap.bind(this);

      var api = 'AIzaSyAfPMecz3Pl6eh5zysrdqbPuyoVImSCYTg';
      var s = document.createElement('script');
      s.src = '//maps.googleapis.com/maps/api/js?key=' + api + '&callback=renderMap';
      s.type = 'text/javascript';
      s.id = 'gmaps-api';
      document.getElementsByTagName("head")[0].appendChild(s);
    }
  }

  renderMap() {
    console.log('called back');
  }
}

Upvotes: 4

Related Questions