I’m creating an object inside some asynchronous JS code. When the object is created I want to call a method on it. I’m a bit stumped how I can refer to the new object to call a method on it.
Here’s my coffeescript. The code adds markers to a google map:
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
And here’s where I invoke this method. I want to call a method on the returned ‘location’ object, but how can I bind in the callback to an object that hasn’t been instantiated yet?
__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)
How can I execute location.setShowInfoWindowOnClick(true)?
In
addLocationyou will want to invoke the callback like;And then in your code;