javascript - typescript access global variable inside listener - Stack Overflow

I have an Angular 2 project and am wanting to test event listeners. this is defined map;then in a popu

I have an Angular 2 project and am wanting to test event listeners. this is defined

map;

then in a populate map method i have

  populateMap() {


var place = { lat: -17.822828, lng: -31.046727 };
this.map = new google.maps.Map(document.getElementById('map'), {
  zoom: 12,
  center: place,
  mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
    position: google.maps.ControlPosition.TOP_RIGHT
  },
  maxZoom: 19
});


this.map.addListener('click', function (e) {
 var marker = new google.maps.Marker({
    position: e.latLng,
    map: this.map
  });
  this.map.panTo(e.latLng);
});


this.map.fitBounds(this.bounds);
this.map.panToBounds(this.bounds);
}

an exception is thrown in the listener of

Uncaught TypeError: Cannot read property 'panTo' of undefined

Is there a reason why javascript is unable to find the correct "this.map" reference, forgot to mention, this is Google Maps API v3

I have an Angular 2 project and am wanting to test event listeners. this is defined

map;

then in a populate map method i have

  populateMap() {


var place = { lat: -17.822828, lng: -31.046727 };
this.map = new google.maps.Map(document.getElementById('map'), {
  zoom: 12,
  center: place,
  mapTypeControlOptions: {
    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
    position: google.maps.ControlPosition.TOP_RIGHT
  },
  maxZoom: 19
});


this.map.addListener('click', function (e) {
 var marker = new google.maps.Marker({
    position: e.latLng,
    map: this.map
  });
  this.map.panTo(e.latLng);
});


this.map.fitBounds(this.bounds);
this.map.panToBounds(this.bounds);
}

an exception is thrown in the listener of

Uncaught TypeError: Cannot read property 'panTo' of undefined

Is there a reason why javascript is unable to find the correct "this.map" reference, forgot to mention, this is Google Maps API v3

Share Improve this question asked Feb 16, 2017 at 15:01 user2168435user2168435 7622 gold badges10 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You are inside of a different context and thus this does not refer to the outer context. You have to keep a reference to it e.g.

var self = this;
this.map.addListener('click', function (e) {
 var marker = new google.maps.Marker({
    position: e.latLng,
    map: self.map
  });
  self.map.panTo(e.latLng);
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745312097a4622045.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信