Как я могу сохранить контекст виджета внутри EventListener в JQuery?

Я строю виджет, который будет создавать карту на основе Google Maps API. Мне трудно использовать контекст виджета внутри слушателя событий. Вот мой код:

(function( $ ) {$.widget( "al.Mappable", {

options: {
  lat: null,
  lng: null,
  bounds: null,
  verbose: true,
  showMap: true,
  googleMap: {
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
},

googleMap: null,
self: null,
_create: function() {
  this.debug("create widget");
  self: this,
  this._setupMap = $.proxy(this._setupMap, this);
  if (this.options.showMap){
    this._setupMap();
  }
},

_setupMap: function(){
  this.debug("init map");
  // debugger;
  if(this.options.lat && this.options.lng){
    this.options.googleMap.center = this._latLng(this.options);
  }
  else{
    //kaboom address
    this.options.lat = 38.945596;
    this.options.lng = -77.064773;
    this.options.googleMap.center = this._latLng(this.options);
  }
  this.googleMap = new google.maps.Map(this.element[0], this.options.googleMap);
  this._addUserLocation(38.945596,-77.064773);


  google.maps.event.addListenerOnce(this.googleMap, 'tilesloaded',this._refreshMap(this.googleMap) );
},

_refreshMap: function(gmap){
  bounds = gmap.getBounds()
  this.options.bounds = bounds
  dataOptions ={
    searching: true,
    keyword: getParam('keyword'),
    playspace_type: getParam('playspace_type'),
    location_type: getParam('location_type'),
    bounds: bounds.toUrlValue()
  }
  // note the 'dummy event' in the callback since ujs sends the event as the first argument
  // $.ajax "/playspaces/search.js",
  //   context: this
  //   data: dataOptions
  //   dataType: 'json'
  //   success: (data,status,xhr) -> @afterResultsAjax('dummyevent',data,status,xhr, false)
 },

_latLng: function(opt){
  return new google.maps.LatLng(opt.lat,opt.lng);
},

});
}( jQuery ));

Когда я делаю ("#map").mappable(), я получаю и ошибку, потому что границы undefined а также toUrlValue() выдает ошибку. объяснение в том, что bounds = gmap.getBounds() срабатывает до этого события tileloaded срабатывает.

Я пытался сделать это:

google.maps.event.addListenerOnce(this.googleMap, 'tilesloaded', function(){
  console.log(this);
});

и я получаю googleMap object назад вместо widget object, Я пытался:

google.maps.event.addListenerOnce(this.googleMap, 'tilesloaded', function(){
  console.log(self);
});

и я получаю window объект.

Вопрос:

Как я могу получить контекст виджета в функции обратного вызова eventListener? Есть ли другой способ дождаться загрузки карты и затем обновить ее маркерами?

0 ответов

Другие вопросы по тегам