Javascript 与';这';在主干视图中

Javascript 与';这';在主干视图中,javascript,backbone.js,Javascript,Backbone.js,所以我有一个谷歌地图的主干视图 'use strict'; var MapView = Backbone.View.extend({ id: 'map-container', initialize: function() { this.model.set('map', new google.maps.Map(this.el, this.model.get('mapOptions'))); this.render(); this.map = this.model

所以我有一个谷歌地图的主干视图

'use strict';

var MapView = Backbone.View.extend({
  id: 'map-container',

  initialize: function() {
    this.model.set('map', new google.maps.Map(this.el, this.model.get('mapOptions')));
    this.render();
    this.map = this.model.get('map');

    this.poly = new google.maps.Polyline({
      strokeColor: '#000000',
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
    this.poly.setMap(this.map);

    this.map.addListener('click', this.addLatLng);
  },

  render: function() {
    $('#map-container').replaceWith(this.el);
    return this;
  },

  addLatLng: function(event) {
    var path = this.poly.getPath();

    path.push(event.latLng);

    var marker = new google.maps.Marker({
      position: event.latLng,
      title: '#' + path.getLength(),
      map: this.map
    });
  }
});

我的问题是addLatLng函数。poly是未定义的,我认为这是因为addLatLng被调用的位置?但我不太确定。有没有办法在addLatLng中定义this.poly和this.map

您希望确保在正确的上下文中调用该方法。 在javascript中,定义这个的是什么

这将实现以下目的:

this.map.addListener('click', this.addLatLng.bind(this));

您希望确保在正确的上下文中调用该方法。 在javascript中,定义这个的是什么

这将实现以下目的:

this.map.addListener('click', this.addLatLng.bind(this));
this.map.addListener('click',this.addLatLng)是您的问题。您正在注册它以运行特定函数,但该函数在运行时不会绑定到任何上下文。可以使用下划线
bind
函数确保函数在当前上下文中运行:

var boundAddLatLong = _.bind(this.addLatLong, this);
this.map.addListener('click', boundAddLatLong);
如果您正在使用某些功能(
on
listenTo
,等等),它提供了提供函数应在其中运行的上下文的方法。但是无论this.map是什么,
似乎都不会这样做。

this.map.addListener('click',this.addLatLng')是您的问题。您正在注册它以运行特定函数,但该函数在运行时不会绑定到任何上下文。可以使用下划线
bind
函数确保函数在当前上下文中运行:

var boundAddLatLong = _.bind(this.addLatLong, this);
this.map.addListener('click', boundAddLatLong);
如果您正在使用某些功能(
on
listenTo
,等等),它提供了提供函数应在其中运行的上下文的方法。但是无论这个.map是什么,
似乎都不会这样做