0

我正在一些异步 JS 代码中创建一个对象。创建对象后,我想在其上调用一个方法。我有点难过如何引用新对象来调用它的方法。

这是我的咖啡脚本。该代码将标记添加到谷歌地图:

addLocation: (name, id, lat, lng, options, callback) ->
  # Add a new location to the map
  # 
  # @param string name - name to give the location
  # @param int id - ID of the location if stored in the database already
  # @param double lat - latitude
  # @param double lng - longitude
  # @param json options - options to use while adding the location
  console.log("Adding new location '#{name}' (#{lat}, #{lng}) to map") if debug

  @__setVisible true, =>
    location = new Location(this, id, name)
    location.setLatLng(lat, lng, options)
    @locations.add(location)

    callback() if callback

    return location

这就是我调用这个方法的地方。我想在返回的“位置”对象上调用一个方法,但是如何在回调中绑定到尚未实例化的对象?

__addLocation: (resultLocation) ->
  # Add a new location to the map and centre the view in on it
  name = $(@nameElement).val() 
  lat = resultLocation.geometry.location.lat()
  lng = resultLocation.geometry.location.lng()

  @map.addLocation name, null, lat, lng, { draggable: true }, ->
    # location doesn't exist at this point so the following line fails
    location.setShowInfoWindowOnClick(true)
    @map.centerMap(location)

如何执行 location.setShowInfoWindowOnClick(true)?

4

1 回答 1

0

addLocation您将要调用回调,例如;

callback location

然后在你的代码中;

@map.addLocation name, null, lat, lng, { draggable: true }, (location) ->
    location.setShowInfoWindowOnClick true
    @map.centerMap location
于 2012-09-01T07:48:46.673 回答