最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - typescript access global variable inside listener - Stack Overflow

programmeradmin0浏览0评论

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);
});
发布评论

评论列表(0)

  1. 暂无评论