How can i keep the context of the widget inside an eventListener in JQuery?

48 views Asked by At

I am building a widget that will create a map based on Google Maps API. I am having a hard time to use the context of the widget inside the event listener. Here is my code:

(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 ));

When i do ("#map").mappable(), i am getting and error because bounds are undefined and toUrlValue() is throwing an error. the explianation is that bounds = gmap.getBounds() is triggered before that the event tileloaded is triggered.

I have tried to do this:

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

and i am getting the googleMap object back instead of the widget object. I have tried:

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

and i am getting the window object.

Question:

How can i get the context of the widget in the eventListener callback function? Is there another way to wait for the map to load and then refresh it with the markers?

0

There are 0 answers