Difference between event handlers and callbacks

ArchitectureCallbackEvent HandlingLanguage Agnostic

Architecture Problem Overview


What is the difference between an event handler and a callback function?

Architecture Solutions


Solution 1 - Architecture

A callback is procedure you pass as an argument to another procedure. The procedure receiving the parameter can call it, or share it so some other procedures in the system can call it.

An event handler is a procedure called when an event happens. It can be a callback.

Solution 2 - Architecture

Generally speaking, a 'callback' is under the control of the detecting process. So you tell a GUI manager "call myaction when this button is pressed" and the GUI manager calls the action when the button is pressed.

Event Handlers on the other hand operate at one step removed. The GUI manager is configured to send messages to an event handler. You tell an event manager that button pushes are handled by the myaction program. When the button is pushed the GUI manager puts a message on the event handler's queue and gets on with GUI managing. The event handler picks up the message from the queue, sees it's a button push, fires up the myaction program, and moves on to handling the next event. Usually the myaction program will run as an independent thread or even a separate process.

While the "event handler" pattern is more complex it is much more robust and less likely to hang when an action fails. It also makes for a more responsive GUI.

Solution 3 - Architecture

An event handler is a type of callback. It's called whenever an event occurs. The term is usually used in terms of user interfaces where events are things like moving the mouse, clicking something and so on.

Solution 4 - Architecture

Events - Think of a Server (Employee) and Client (Boss).One Employee can have many Bosses. The Employee Raises the event, when he finishes the task, and the Bosses may decide to listen to the Employee event or not.The employee is the publisher and the bosses are subscriber.

Callback - The Boss specifically asked the employee to do a task and at the end of task done, the Boss wants to be notified. The employee will make sure that when the task is done, he notifies only the Boss that requested, not necessary all the Bosses. The employee will not notify the Boss, if the partial job is done. It will be only after all the task is done.Only one boss requested the info, and employee only posted the reply to one boss.

Solution 5 - Architecture

Callback (from Wikipedia): "executable code that is passed as an argument to other code".
Event handler (again from Wikipedia): "asynchronous callback subroutine that handles inputs received in a program".

Which happens to be the way I've always understood it: an event handler is a very specific type of callback.

Solution 6 - Architecture

This question is very old but I found this link from MSDN very interesting. I hope anyone else that stumbles on this question gets something out of this link.

Solution 7 - Architecture

Another aspect of this is that events describe something that happened in the past, whereas a callback is often used while something is happening.

When an event fires, you're being told that something has happened. When a callback is used, you're being asked to participate in something.

A library or framework might issue events that let you know something has happened. A framework offers you points at which you can plug in code (perhaps as callbacks) so that you can take actively part in a process.

Part of the problem is that event, callback refer to technical mcehanisms as well as more abstract processes.

Solution 8 - Architecture

An event handler is a callback too. Its just more decoupled.

Traditionally a process "A" would pass the pointer to one of it's method(callback) to an external process "B" so that B can invoke it later based on the logic implemented.

For e.g. Let's say our goal is to check if an API call succeeded.

If it did, we store a value "success" in a variable and if it did not, then we store "failed" in it. This variable is updated by a function "checkIfAPICallSucceded" in our program "P", which accepts the API response as an argument to decide the fate of this variable.

Here is how a normal callback scenario would implement it:

  • Step 1: P makes an API call
    • Note 1.1: The API call itself is handled by a separate process "Q" (say a network program)
    • Note 1.2: Let's imagine P waits (blocks or sleeps) until Q has the result
    • Note 1.3: So Q needs to let P know when the response arrives
    • Note 1.4: Therefore P needs to hand over the pointer to the function "checkIfAPICallSucceded"(callback) to Q while making the API call
  • Step 2: P passes the pointer to "checkIfAPICallSucceded" along with the call
  • Step 3: Q receives the request for the API call along with callback's pointer
  • Step 4: Q receives the response from the API call and passes it along with the pointer to P
  • Step 5: P calls the callback with the response as the argument.

Problem here is that Q knows "too" much about P (memory address of the callback within P). This may not be ideal.

Within event handlers, the difference is the callback itself is never passed to Q. Instead, upon receiving the response Q simply announces an event (an object containing the status and the data of the response). Yet another program called an event loop "EL" (this is a simple program that listens for events) manages the execution of the callback.

  • Step 1: P makes an API call to Q
    • Note 1.1: As notified above, Event handler models have yet another program or process called "EL"
    • Note 1.2: P passes the event handler (callback) to EL instead of Q
    • Note 1.3: EL does 2 things - it maintains a table with pointers to registered callbacks and it also continuously checks a memory structure called event queue for event objects
    • Note 1.4: After making the API call to Q and registering the event handler with EL, P doesn't wait and carries on executing the next statements
  • Step 2: Upon receiving the response, Q pushes the event "e" to the event queue
  • Step 3: EL then picks up "e" during its next loop
  • Step 4: EL then calls the corresponding callback from the table with e as the argument

This way Q never knows anything about P. In fact Q may not even directly push e to the event queue and the OS may do it on its behalf and in such a case Q would not even know about EL.

Having an event loop to handle callback results in following benefits:

  • the callbacks can be fired once P is free from its current execution tasks (this can avoid spinning up separate threads and the resulting thread management headaches)
  • the event queue can keep storing events avoiding blocking Q who would otherwise need to block until the first event is serviced by P.

Event handler model therefore requires an additional program (EL) and therefore additional resource(CPU time and memory). It is best suited for I/O operations where it is almost sure that those programs are developed by an entirely different team (therefore low trust levels)

Simple callbacks where Q "knows" about P may sound unpleasant but when its the same team(high trust levels) that creates both Q and P, simple callbacks can save resources.

Solution 9 - Architecture

The underlying mechanisms are similar, but the semantics are different. Both callbacks and event handlers are called asynchronously.

The callback function is generally passed explicitly from a caller routine to request some information. The information is returned some time later, passed as arguments back to the callback by the callee. At this time, the calling routine completes its business. Often the callback is a closure - syntactically inside the calling routine, and often un-named (anonymous). It might look a bit like the below, in javascript:

function caller() {
    someLibrary.getMeSomething(arg1, arg2, function(returnedData) {
        // this is the callback which will do something with returnedData
    });
}

So the callee (someLibrary.getMeSomething) is given an anonymous callback function, and some time later this function is called with the returnedData. A callback is like a single-shot event to a single receiver.

Events handlers are also 'called back', but generally they are used over an extended period for multiple events, like mouse clicks, network events etc. Also, multiple objects may be interested in the same event. For these reasons, you generally 'subscribe' or 'register' to events in setup code (like object initialisation), and the event handler is more typically a named method. Usually too, each event type is identified as a constant or string.

So in Python it might look like:

class MyUIClass:

    def __init__(self):
        someUILib.register(someUILib.events.MOUSE_CLICK, self.my_mouse_click_handler);

    def my_mouse_click_handler(self, eventInfo):
        # do something with event
        if eventInfo.x < 100:
             print 'You clicked in the margin'

Solution 10 - Architecture

A callback is function(method) you pass as an argument to another function(method). The function(method) receiving the parameter can call it, or share it so some other function(method) in the system can call it.

An event handler is a function(method) called when an event happens. It can be a callback.

Solution 11 - Architecture

Event callbacks and handlers, at the highest abstract level, are the same i.e. you have an event and a response to that event. (A response is just a piece of code that needs to run in response to something that happened.) The difference between the two lies in the fact that if this code is directly or indirectly invoked. In the case of callbacks, the code i.e. the callback itself is directly invoked. In the case of event handlers, this event is first communicated or notified to the right recipient and then from then on, the code is then invoked.

Solution 12 - Architecture

An event has special features like bubbling and so on. If you do not need those features, then just use a callback.

Solution 13 - Architecture

Callback is for asking another function to do business operations and send a result whereas events are not but asking for handover the control so that we can only handle business operation.

Eg: Button click is event (We are doing business operation on click of button). Looping collections in callback since forEach method is doing business operation and providing result.

Solution 14 - Architecture

Event handler is a callback from the system.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaron SView Question on Stackoverflow
Solution 1 - ArchitectureCarlos GutiérrezView Answer on Stackoverflow
Solution 2 - ArchitectureJames AndersonView Answer on Stackoverflow
Solution 3 - ArchitecturecletusView Answer on Stackoverflow
Solution 4 - ArchitectureTanuADView Answer on Stackoverflow
Solution 5 - ArchitectureEsteban ArayaView Answer on Stackoverflow
Solution 6 - ArchitectureuriDiumView Answer on Stackoverflow
Solution 7 - ArchitectureTim BarrassView Answer on Stackoverflow
Solution 8 - ArchitecturesupiView Answer on Stackoverflow
Solution 9 - ArchitecturepwrayView Answer on Stackoverflow
Solution 10 - ArchitecturetrableView Answer on Stackoverflow
Solution 11 - ArchitectureChris TaylorView Answer on Stackoverflow
Solution 12 - ArchitectureIniView Answer on Stackoverflow
Solution 13 - ArchitectureEdisonView Answer on Stackoverflow
Solution 14 - ArchitectureRevenantView Answer on Stackoverflow