Oh, probably the reason every click says "10" there is that there is
only one variable i, it's defined outside the "map", and it gets
mutated up to 10. Speaking in terms of closures, all the handlers
"close over" that one single variable binding, they don't each "close
over" their own variable binding, because there only is one. To get
the latter you'd need to have a variable whose scope is equal to the
map.
I'm not sure you should be using a map there. Maybe just a foreach
would do? An each_with_index would give you e and i, and they'd be
block-scoped like you want.
I'm not sure what the "append do" is doing in the main stack? You
don't need to append when you first lay out the app, just if you're
modifying it later on.
This code actually just crashes for me on OS X though -- crashes
during the click handler! I've been fiddling around trying to figure
out why it crashes with no luck so far.
On Jul 25, 2008, at 6:12 PM, Martin DeMello wrote:
What's going on in the below code? I expected each number to capture
the current value of i in its click callback, but every click says
"10"
martin
Shoes.app :width => 840, :height => 700, :title => "Test" do
def list_view(ary)
i = -1
ary.map {|e|
i = i + 1
flow do
background (i % 2 == 0 ? lightblue : white)
para e, :size => 8
click do
alert i
end
end
}
end
background white
stack :width => 280, :margin_top => 20, :margin_left => 10, :height
=> 600 do
@listview = stack :width => 275, :margin => 10, :height => 580,
:scroll => true do
background white
append do
list_view (0..10).to_a
end
end
end
end