Javascript:对回调创建的对象执行方法

Javascript: Execute method on object created by callback

本文关键字:对象 执行 方法 创建 回调 Javascript      更新时间:2023-09-26

我正在一些异步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

这里是我调用这个方法的地方。我想对返回的"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)?

addLocation中,您将希望调用回调,如;

callback location

然后在你的代码中;

@map.addLocation name, null, lat, lng, { draggable: true }, (location) ->
    location.setShowInfoWindowOnClick true
    @map.centerMap location