微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Backbone.js与谷歌地图 – 这个和听众的问题

我有一个我为Google Maps v3创建的模块,我正在尝试将其转换为Backbone.js视图构造函数.

到目前为止,这是我的视图模块:我将在代码后解释我遇到的问题:

pg.views.CreateMap = Backbone.View.extend({

  tagName:  "div",className: "map",events: {},latitude:   "-23.56432",longitude:  "-46.65183",initialize: function() {
    _.bindAll(this,'render','dragMarker','dragMap');

    this.latlng = new google.maps.LatLng(this.latitude,this.longitude);
    var myOptions = {
      zoom: 16,center: this.latlng,mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map($(this.el)[0],myOptions);
    this.marker = new google.maps.Marker({
      map: this.map,position: this.latlng,draggable: true
    });

    google.maps.event.addListener(this.marker,"dragend",this.dragMarker());

    google.maps.event.addListener(this.map,this.dragMap());

  },render: function() {
    return this;
  },dragMarker: function() {
    this.latlng = this.marker.getPosition();
    this.map.panTo(this.latlng);
  },dragMap: function() {
    this.latlng = this.map.getCenter();
    this.marker.setPosition(this.latlng);
  }

});

我遇到的问题是Google Maps事件监听器以及如何处理“this”.

我最初没有dragMarker和dragMap方法,而是在initialize块中使用了这两个:

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

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

我在第一种方法中遇到的问题是这些匿名函数中的“this”分别称为“this.marker”和“this.map”.第一种方法的问题是在第一个监听器中,我无法引用“this.map”,因此无法执行panTo().对于第二个监听器,我无法引用“this.marker”,因此无法使用setPosition()重新定位该标记周围的地图.

然后我想我可以在监听器中取出匿名函数并将它们声明为视图的方法,然后我将执行_.bindAll(this,“dragMarker”,“dragMap”);

这种方法的问题是我必须在事件块中编写监听器,如下所示:

google.maps.event.addListener(this.marker,this.dragMarker());

google.maps.event.addListener(this.map,this.dragMap());

这意味着当我使用newmap = new pg.views.CreateMap调用构造函数时;当触发“dragend”事件时,立即评估“this.dragMarker()”和“this.dragMap()”而不是被评估为回调.

没问题,我想,然后将这些包装在匿名函数中,function() { this.dragMarker(); }); google.maps.event.addListener(this.map,function() { this.dragMap(); });

不幸的是,这也让我回到了早先的问题,即“this.dragMarker”中的“this”不再引用我构造的父对象,而是再次引用“this.marker”.第二个侦听器出现同样的问题.

我完全被困在这里了.任何人对我如何解决这个问题都有任何想法?

解决方法

使用dragend上调用的匿名函数并显式绑定.
_.bindAll(this,'dragMap');
google.maps.event.addListener(this.marker,this.dragMarker);
/* etc ... */

这样,即使在上下文外调用,它也始终与CreateMap绑定.

原文地址:https://www.jb51.cc/js/158803.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐