Coding clarity of closure for load event

前端 未结 1 468
别那么骄傲
别那么骄傲 2020-12-12 05:02

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 = $(\"

        
1条回答
  •  旧巷少年郎
    2020-12-12 05:27

    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 = $("")
        new_item.on 'load', => @add_item(item)
        $("#preload-area").append(new_item)        
    

    0 讨论(0)
提交回复
热议问题