虽然这是一篇旧帖子,但我想为未来的谷歌用户增加一些对话内容。
OP 是正确的,我们不能在纯 CoffeeScript 中声明函数(不包括使用反引号在 CoffeeScript 文件中转义纯 JS 的想法)。
但是我们可以将函数绑定到窗口,并最终得到类似于命名函数的东西,可以像调用函数 foo(param) 一样在代码中的某处调用。我并不是在说这是一个命名函数,我提供了一种使用纯 CoffeeScript 实现 OP 想要实际执行的操作(调用函数)的方法。
以下是一个示例,在 coffeescript 中附加到窗口的函数:
window.autocomplete_form = (e) ->
autocomplete = undefined
street_address_1 = $('#property_street_address_1')
autocomplete = new google.maps.places.Autocomplete(street_address_1[0], {})
google.maps.event.addListener autocomplete, "place_changed", ->
place = autocomplete.getPlace()
i = 0
while i < place.address_components.length
addr = place.address_components[i]
st_num = addr.long_name if addr.types[0] is "street_number"
st_name = addr.long_name if addr.types[0] is "route"
$("#property_city").val addr.long_name if addr.types[0] is "locality"
$("#property_state").val addr.short_name if addr.types[0] is "administrative_area_level_1"
$("#property_county").val (addr.long_name).replace(new RegExp("\\bcounty\\b", "gi"), "").trim() if addr.types[0] is "administrative_area_level_2"
$("#property_zip_code").val addr.long_name if addr.types[0] is "postal_code"
i++
if st_num isnt "" and (st_num?) and st_num isnt "undefined"
street1 = st_num + " " + st_name
else
street1 = st_name
street_address_1.blur()
setTimeout (->
street_address_1.val("").val street1
return
), 10
street_address_1.val street1
return
这是使用Google Places返回地址信息并自动填充表单。在Rails应用程序中,我们有一个部分被加载到页面中。这意味着DOM已经创建,如果我们在初始页面加载时调用上述函数(在ajax调用渲染部分之前),jQuery将无法看到$('#property_street_address_1')元素(相信我-它没有)。因此,我们需要延迟google.maps.places.Autocomplete(),直到元素出现在页面上。我们可以通过Ajax回调来实现这一点,在部分成功加载后进行。
url = "/proposal/"+property_id+"/getSectionProperty"
$("#targ-"+target).load url, (response, status, xhr) ->
if status is 'success'
console.log('Loading the autocomplete form...')
window.autocomplete_form()
return
window.isSectionDirty = false
所以在这里,本质上我们做的是调用foo()函数。
class
中使用函数声明的原因。 - Trevor Burnham