0

第一个和第二个有什么不同?第一个按预期工作,但第二个没有达到我的预期。在第一个中,我通过 callToPhotos 间接进行调用,但在第二个中,我立即调用 getPhotos 并传入相册。为什么以及如何不同?

$.ajax
    method:'get'
    url: '/slides/facebook-albums'
    success: (albums) ->
        renderAlbums(albums)
        callToPhotos(albums)

renderAlbums = (albums) ->
    for album in albums
        $('#facebook .main').append("<div id='#{ album['id'] }' class='album-info'><a class='#{album['id']} fb-album' href='#'>#{album['name']}</a>
        <img src=#{album['cover_photo']} width='100' height= '100' class='#{album['id']} fb-album'></div>")

callToPhotos = (albums) ->
    for album in albums
        getPhotos(album)

getPhotos = (album) ->
      $.ajax
        method: "get"
        url: "/slides/#{album['id']}/photos"
        success: (photos) ->
          renderPhotos(photos, album['id'])

--

$.ajax
    method:'get'
    url: '/slides/facebook-albums'
    success: (albums) ->
        renderAlbums(albums)
        # callToPhotos(albums)
        getPhotos(albums)

renderAlbums = (albums) ->
    for album in albums
        $('#facebook .main').append("<div id='#{ album['id'] }' class='album-info'><a class='#{album['id']} fb-album' href='#'>#{album['name']}</a>
        <img src=#{album['cover_photo']} width='100' height= '100' class='#{album['id']} fb-album'></div>")

callToPhotos = (albums) ->
    for album in albums
        getPhotos(album)

getPhotos = (albums) ->
    for album in albums
      $.ajax
        method: "get"
        url: "/slides/#{album['id']}/photos"
        success: (photos) ->
          renderPhotos(photos, album['id'])
4

1 回答 1

1

它与第二个片段循环中的变量范围有关。您可以引入一个立即调用函数 (IIF) 来解决它(阅读http://coffeescript.org/#loopsdo部分底部的关键字=D):

getPhotos = (albums) ->
  for album in albums
    do (album) ->
      $.ajax
        method: "get"
        url: "/slides/#{album['id']}/photos"
        success: (photos) ->
          renderPhotos(photos, album['id'])
  return

不过,我确实建议您使用第一种方法,因为它与 IIF 相同,但我认为更清楚,因为额外函数现在具有描述性变量名称;也许在函数内部声明getPhotos函数:

getPhotos = (albums) ->
  getAlbum = (album) ->
    $.ajax
      method: "get"
      url: "/slides/#{album['id']}/photos"
      success: (photos) ->
        renderPhotos(photos, album['id'])

  getAlbum album for album in albums

  return

(请注意,在这两种情况下,我都添加了一个空return,这样它就不会生成并返回数组理解作为其最后一个表达式 =P)

于 2013-04-25T05:36:08.327 回答