& # 39;这个# 39;没有在backbone.js视图中定义

'this' is not defined within a backbone.js view

本文关键字:js 视图 定义 backbone 这个      更新时间:2023-09-26

我正试图实现谷歌地图api作为一个backbone.js视图。这是目前为止自动完成函数的代码:

    address_search_listen: function(){
    //create a new auto complete object
    var map= this.map;
    var autocomplete = new google.maps.places.Autocomplete((document.getElementById('address_search')),{types: ['geocode'] });
        google.maps.event.addListener(autocomplete, 'place_changed',function(){
                var place = autocomplete.getPlace();
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(0, 0),
                    map: map,
                    title: "test"
                 });
        });
}

在事件处理程序中没有定义变量map。我试过几件事都没有成功。有人能帮我一下吗?

为了回答你的问题,最好先知道你的主干视图结构。具体来说,就是创建google map实例和调用函数address_search_listen的地方。

如果你确定谷歌地图实例被创建并成为你的view对象的属性,一个可能的原因,导致你有未定义的变量mapthis指的是其他对象而不是你的view对象。

正如上面@Manuish建议的那样,使用_。绑定设置处理程序的作用域:

_.bind( this, function(){
  var place = autocomplete.getPlace();
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(0, 0),
      map: map,
      title: "test"
  })
);