问题
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
dokeyword, 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