Annonymous functions and foreach usage on event-driven code in julia

Viewed 46

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))

Mainly I can't see how on_click() gets the event from click(). Can anyone shed some light on it?

1 Answers

What might not be obvious is how the handlers array are filled, namely by applying on_click() twice.

on_click(handler) = push!(handlers, handler)

defines a function that adds a handler, whereas

on_click() do event
    println("Mouse clicked at $event")
end

on_click() do event
    println("Beep.")
end

calls this newly defined function twice. The do notation hides this a little bit but basically this translates to:

push!(handlers, event -> println("Mouse clicked at $event"))
push!(handlers, event -> println("Beep."))

What follows when click() is called is that the element provided e.g. (x=50, y=29) is passed to all handlers using the foreach construct.

Related