Closing Sphere not captured? - coffeescript

Well, I do not know how to formulate a heading for this question.

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"

I understand that a variable is itemBoxdefined in the scope openDirhere. But since the specified string is in a lambda function, shouldn't it itemBoxcommit the object referenced by the itemBoxparent area, instead of being mutated to the last object it refers to?

To express this, I expect that the click handler of each itemBoxwill execute addClass "selected"for itself. But what happens is that itemBoxin each of the click handlers, it always refers to the last itemBox.

I can easily fix this by changing where itemBox is declared. those. change

for item in data.contents

at

data.contents.forEach (item) ->

, .

+5
1

:

for item in data.contents
    itemBox = $ "<div/>", class: "itembox"

, (Coffee | Java) Script. :

itemBox = undefined
for item in data.contents
    itemBox = $ "<div/>", class: "itembox"

itemBox . itemBox, , , itemBox, itemBox .

:

JavaScript , , , . CoffeeScript do, , .

, :

for item in data.contents
    do (item) ->
        # As before...

itemBox .

forEach:

data.contents.forEach (item) ->

, , .

+9

All Articles