home *** CD-ROM | disk | FTP | other *** search
/ Archive Magazine 1996 / ARCHIVE_96.iso / discs / mag_discs / volume_9 / issue_04 / cpp / callback
Text File  |  1995-10-28  |  2KB  |  68 lines

  1. // callback.h
  2.  
  3. // by Tony Houghton
  4.  
  5. // version 1.00 (28 Oct 1995)
  6.  
  7. #ifndef __callback_h
  8. #define __callback_h
  9.  
  10. #ifndef __event_h
  11. #include "event.h"
  12. #endif
  13.  
  14. /*
  15.   Any class to be called by a TboxCallback must have a method:
  16.   int callback(int event_code, EventStruct *event, IdBlock *);
  17.   Note lack of final void *handle argument, any additional data
  18.   can be contained within handler object.
  19.   Ideally we should be able to pass a method as an argument
  20.   of the TboxCallback class, but a bug in Acorn C++ prevents it.
  21.   A fixed function name is not too restricting, it can be overloaded
  22.   for different EventStructs
  23. */
  24.  
  25. template<class HandlerClass, class EventStruct>
  26. // HandlerClass is the class of object the event will be passed to.
  27. // EventStruct is the type the ToolboxEvent will be cast to
  28. class TboxCallback {
  29.   int event_code;
  30.   int object_id;
  31.   HandlerClass *handler;
  32.     // It is usually more convenient to pass a pointer to the handler
  33.     // object than a reference, so you can create a TboxCallback
  34.   static int f(int code, ToolboxEvent *event, IdBlock *id_block, void *handle)
  35.   {
  36.     // handle is used to point to the relevant TboxCallback
  37.     TboxCallback<HandlerClass, EventStruct> &callback =
  38.     *((TboxCallback<HandlerClass, EventStruct> *) handle);
  39.     return callback.handler->callback(code, (EventStruct *) event, id_block);
  40.   }
  41. public:
  42.   TboxCallback(HandlerClass *that, int code, ObjectId id = -1)
  43.       : event_code(code), object_id(id), handler(that)
  44.   {
  45.     event_register_toolbox_handler(id, event_code, f, this);
  46.   }
  47.   ~TboxCallback()
  48.   {
  49.     event_deregister_toolbox_handler(object_id, event_code, f, this);
  50.   }
  51. };
  52.  
  53. /*
  54.   So to register a callback for Window_AboutToBeShown for example,
  55.   from a method of a class called MainWindow with members:
  56.   ObjectId win_id;
  57.   and
  58.   TboxCallback<MainWindow, WindowAboutToBeShownEvent> *cb;
  59.   you could use:
  60.  
  61.   cb = new TboxCallback<MainWindow, WindowAboutToBeShownEvent>
  62.        (this, Window_AboutToBeShown, win_id);
  63.  
  64.   To deregister the callback simply delete cb
  65. */
  66.  
  67. #endif
  68.