CoffeeScript for循环不能采取多个动作?

时间:2013-04-25 04:48:26

标签: javascript coffeescript

第一个与第二个有什么不同?第一个按预期工作,但第二个没有按照我的预期进行。在第一个我通过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'])

1 个答案:

答案 0 :(得分:1)

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

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)