I'm currently following Julia for pythonistas notebook by Aurelien Geron (https://github.com/ageron/julia_notebooks) and I'm a bit confused on annonymous functions chapter with the following code:
handlers = []
on_click(handler) = push!(handlers, handler)
click(event) = foreach(handler->handler(event), handlers)
on_click() do event
println("Mouse clicked at $event")
end
on_click() do event
println("Beep.")
end
click((x=50, y=20))
click((x=120, y=10))
Run Code Online (Sandbox Code Playgroud)
Mainly I can't see how on_click()
gets the event
from click()
. Can anyone shed some light on it?
小智 5
可能不明显的是handlers
数组是如何填充的,即通过应用on_click()
两次。
on_click(handler) = push!(handlers, handler)
Run Code Online (Sandbox Code Playgroud)
定义了一个添加处理程序的函数,而
on_click() do event
println("Mouse clicked at $event")
end
on_click() do event
println("Beep.")
end
Run Code Online (Sandbox Code Playgroud)
两次调用这个新定义的函数。在do
这个符号揣一点点,但基本上都是这样的语句:
push!(handlers, event -> println("Mouse clicked at $event"))
push!(handlers, event -> println("Beep."))
Run Code Online (Sandbox Code Playgroud)
click()
调用when 之后的内容是将提供的元素(例如(x=50, y=29)
)传递给使用该foreach
构造的所有处理程序。
归档时间: |
|
查看次数: |
43 次 |
最近记录: |