Wednesday, April 18, 2012

How to disable an eventhandler when another is getting called

I have two event listeners on one input field. One gets called on change and one when you click on an autocomplete dropdown from google. My problem is when you click on such a autocompletion both handlers get called and make the request to the google api.



I tried to bind the onchange event and unbind it when the google autocomplete ajax call get fired, but the onchange event is executed first. So it will not get unbinded.
So, is there any possibility to detect if the user made the input manually or via autosugesstion? I want to execute the "requestlocation" function only when the user makes a manually input and doesn't use the autocomplete dropdown.
I tried it with some other eventhandler like "focus-out", but without success.



This line makes the bind:



autoCompleteInput.on "change", requestlocation


This is the function which get called:



requestlocation = () ->
address = autoCompleteInput.val()
geocoder = new google.maps.Geocoder()
geocoder.geocode
address: address, (results, status) ->
if status is google.maps.GeocoderStatus.OK

if results[0].address_components.length > 1
city = results[0].address_components[0].long_name
country = results[0].address_components[results[0].address_components.length-1].long_name
setHiddenFields results[0].geometry.location.lat(), results[0].geometry.location.lng(), city, country
autoCompleteInput.val(city+", "+country)
else
city = null
country = results[0].address_components[0].long_name
setHiddenFields results[0].geometry.location.lat(), results[0].geometry.location.lng(), city, country
autoCompleteInput.val(country)
setMarker new google.maps.LatLng(latInput.val(), lngInput.val())
else
console.log "Geocode was not successful for the following reason: " + status


This is the code where the autocomplete handler makes the request:



google.maps.event.addListener autocomplete, 'place_changed', ->
autoCompleteInput.off "change", requestlocation

place = autocomplete.getPlace()

if !!place.geometry
autoCompleteInput.attr "data-valid", "true"
setMarker place.geometry.location
address = place.address_components
if address.length > 1
setHiddenFields place.geometry.location.lat(), place.geometry.location.lng(), address[0].long_name, address[address.length-1].long_name
else
setHiddenFields place.geometry.location.lat(), place.geometry.location.lng(), null, address[0].long_name
else
autoCompleteInput.attr "data-valid", "false"

autoCompleteInput.on "change", requestlocation


Thanks for any answers!





No comments:

Post a Comment