Difference between event handlers and callbacks

前端 未结 12 2559
时光说笑
时光说笑 2020-12-22 16:33

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

12条回答
  •  悲哀的现实
    2020-12-22 17:11

    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'
    

提交回复
热议问题