Backbone.js with Google Maps - problems with this and listeners

心已入冬 提交于 2019-12-02 21:16:44

Take the anonymous functions called on dragend and bind explicitly.

_.bindAll(this, 'dragMarker', 'dragMap');
google.maps.event.addListener(this.marker, "dragend", this.dragMarker);
/* etc ... */

This way this will always be tied to CreateMap even if called out of context.

I solved this problem by using the that/self hack common in Javascript.

var self = this;

google.maps.event.addListener(this.marker, "dragend", function() {
  self.latlng = this.getPosition();
  self.map.panTo(self.latlng);
});

google.maps.event.addListener(this.map, "dragend", function() {
  self.latlng = this.getCenter();
  self.marker.setPosition(self.latlng);
});

If anyone has a solution that doesn't require this hack, I'm all ears.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!