Coding clarity of closure for load event

心已入冬 提交于 2019-12-17 21:17:20

问题


Is there are clear way to write this closure for the load event on line #4:

for i,item of m
  # add item once image loaded
  new_item = $("<img src='#{util.image_url(item, 'large')}' />")
  new_item.on 'load', ((item) => (=> @add_item(item)))(item)
  $("#preload-area").append(new_item)

回答1:


You want a do loop:

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

Something like this:

for i, item of m
  do (item) =>
    new_item = $("<img src='#{util.image_url(item, 'large')}' />")
    new_item.on 'load', => @add_item(item)
    $("#preload-area").append(new_item)        


来源:https://stackoverflow.com/questions/20057967/coding-clarity-of-closure-for-load-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!