好吧,我不知道如何为这个问题标题。未收集关闭范围? - Coffeescript
openDir = (path) ->
socket.emit "get_metadata", path, (data) ->
columnBox = $ "<div/>", class: "columnbox"
for item in data.contents
itemBox = $ "<div/>", class: "itembox"
itemBox.click ->
columnBox_inner.children().removeClass "selected"
itemBox.addClass "selected" # <<<--- Over here
openDir item.path
columnBox.append itemBox
columnBox.appendTo "#columnscontainer"
据我所知,可变itemBox
下openDir
的范围在此定义。但是由于指出的行是在lambda函数中,因此不应该在itemBox
那里捕获父范围的itemBox
引用的对象,而不是突变到它引用的最后一个对象?
说得很清楚,我希望每个itemBox
的点击处理程序自己执行addClass "selected"
。但是会发生什么情况是每个点击处理程序中的itemBox
始终引用最后一个itemBox。
我可以通过更改itemBox被声明的位置来轻松解决此问题。即改变
for item in data.contents
到
data.contents.forEach (item) ->
但我想知道为什么lambda函数不捕获变量的当前值。
该问题也适用于'openDir item.path'行中引用的'item'变量,因为即使在'openDir'范围内定义了该变量。 – 2012-08-16 22:44:18