2013-10-01 47 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

相关问题