0

I have method in component like mentioned here.

export class MapComponent implements OnInit {

  map: any;
  dataLayer: any;
  infoBoxLayer: any;
  infobox: any;
  infoBoxCollection = [];

LoadMapView() {
    var that = this;

    var location = new Microsoft.Maps.Location(40.0583, -74.4057);

    this.map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
      credentials: this.config.get('BingMapKey'),
      center: location,
      mapTypeId: Microsoft.Maps.MapTypeId.road,
      zoom: this.lastZoomLevel,
      liteMode: true,
      enableClickableLogo: false,
      showLogo: false,
      showTermsLink: false,
      showMapTypeSelector: false,
      showTrafficButton: true,
      enableSearchLogo: false,
      showCopyright: false
    });

    // Create a layer to load pushpins to.
    this.dataLayer = new Microsoft.Maps.EntityCollection();
    this.infoBoxLayer = new Microsoft.Maps.EntityCollection();
    this.map.entities.push(this.infoBoxLayer);

    var metadata = {
      Id: '12345',
      title: 'testing'
    }

    NewPin = new Microsoft.Maps.Pushpin(location, { icon: '../icon/pin.png' });

    this.map.entities.push(NewPin);

    this.dataLayer.push(NewPin);

    Microsoft.Maps.Events.addHandler(NewPin, 'click', pushpinClicked);

    this.infobox = new Microsoft.Maps.Infobox(maps.getCenter(), {
        visible: false
    });

    function pushpinClicked(e) {

      if (e.target.metadata) {
        that.infobox.setMap(maps);
        that.infobox.setOptions({
          location: e.target.getLocation(),
          visible: true,
          showCloseButton: true,
          offset: new Microsoft.Maps.Point(0, 20),
          htmlContent: '<div class = "infy" style= "background-color: white;border: 1px solid lightgray; width:520px;">'
            + e.target.metadata + '</div>'
        });
        // push this infoBox
        that.infoBoxCollection.push(that.infobox);
        }
    }
}}

I have assigned "this" reference to "that" variable in LoadMapView() because I am not able to get local variable in pushpinClicked function using this reference.

Is there anyway to avoid "that" variable to access reference of this variable ?

I am facing memory leak problem because of "that" variable"

Pushkar Rathod
  • 353
  • 2
  • 7
  • 26
  • The two techniques most often suggested are: (1) define the callback as an arrow function; (2) use `.bind(this)` (e.g. `pushpinClicked.bind(this)`). – ConnorsFan Feb 28 '18 at 01:50

1 Answers1

1

Change

function pushpinClicked(e) {...

...to...

const pushpinClicked = (e) => {...
kshetline
  • 12,547
  • 4
  • 37
  • 73