简体   繁体   中英

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?

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');
  }
}

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