2013-10-01 42 views
0

我想多谷歌的地方自動完成場在同一個頁面整合,我只是想不通,爲什麼這個僞代碼工作:CoffeeScript的環比谷歌的地方自動完成

$ -> 
    options = types: ["(cities)"] 

    insts = [] 
    elements = document.getElementsByClassName('autocomplete_city') 

    insts[0] = new google.maps.places.Autocomplete(elements[0], options) 
    google.maps.event.addListener insts[0], "place_changed", -> 
    place = this.getPlace() 
    datas = place.geometry.location.lat()+"::"+place.geometry.location.lng() 

    $(elements[0]).next('input.autocomplete_city_id').val(datas) 


    insts[1] = new google.maps.places.Autocomplete(elements[1], options) 
    google.maps.event.addListener insts[1], "place_changed", -> 
    place = this.getPlace() 
    datas = place.geometry.location.lat()+"::"+place.geometry.location.lng() 

    $(elements[1]).next('input.autocomplete_city_id').val(datas) 

雖然這個循環版本不工作:

$ -> 
    options = types: ["(cities)"] 

    insts = [] 
    elements = document.getElementsByClassName('autocomplete_city') 

    i = 0 
    for element in elements 
    insts[i] = new google.maps.places.Autocomplete(element, options) 

    google.maps.event.addListener insts[i], "place_changed", -> 
     place = this.getPlace() 
     datas = place.geometry.location.lat()+"::"+place.geometry.location.lng() 

     $(element).next('input.autocomplete_city_id').val(datas) 

    i += 1 

在這種情況下,只有最後的「autocomplete_city_id」與自動完成DATAS填滿,即使你在第一個自動完成輸入(=「元」鍵入reciever變量總是陣列中的最後一個)

不是那兩個片段完全相同還是我缺少一些嚴重的Javascript OOP原則?這是一個Coffeescript陷阱嗎?

回答

2

上的CoffeeScript的網站上提到:

當使用JavaScript的循環產生的功能,這是常見的,以保證循環變量被關閉了插入一個封閉的包裝,和所有的生成函數不只是分享最終值。 CoffeeScript提供了do關鍵字,它立即調用傳遞的函數,轉發任何參數。

你也許可以修改您的代碼,因爲這:

$ -> 
    options = types: ["(cities)"] 

    insts = [] 
    elements = document.getElementsByClassName('autocomplete_city') 

    i = 0 
    for element in elements 
    do (element) -> 
     insts[i] = new google.maps.places.Autocomplete(element, options) 

     google.maps.event.addListener insts[i], "place_changed", -> 
     place = this.getPlace() 
     datas = place.geometry.location.lat()+"::"+place.geometry.location.lng() 

     $(element).next('input.autocomplete_city_id').val(datas) 

     i += 1 

別的東西:for語句可以使用像for element, index。然後您可以刪除i = 0及其增量。

0

我的建議是奇怪的行爲可能是編譯後的js中push方法造成的。

我重構了你的代碼,並在循環中添加了return

$ -> 
    options = types: ["(cities)"] 

    insts = [] 
    elements = document.getElementsByClassName('autocomplete_city') 

    for element, i in elements 
    insts[i] = new google.maps.places.Autocomplete(element, options) 

    google.maps.event.addListener insts[i], "place_changed", -> 
     place = @.getPlace() 
     datas = "#{place.geometry.location.lat()}::#{place.geometry.location.lng()}" 
     $(element).next('input.autocomplete_city_id').val(datas) 
     return 
    return 
+0

是的,這工作,謝謝:-)。儘管如此,Franck的下一個回答指出瞭解決這個問題的「cooffeescript方式」。 – gbarillot

相關問題