ein-events.el 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. ;;; ein-events.el --- Event module
  2. ;; Copyright (C) 2012- Takafumi Arakaki
  3. ;; Author: Takafumi Arakaki <aka.tkf at gmail.com>
  4. ;; This file is NOT part of GNU Emacs.
  5. ;; ein-events.el is free software: you can redistribute it and/or modify
  6. ;; it under the terms of the GNU General Public License as published by
  7. ;; the Free Software Foundation, either version 3 of the License, or
  8. ;; (at your option) any later version.
  9. ;; ein-events.el is distributed in the hope that it will be useful,
  10. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. ;; GNU General Public License for more details.
  13. ;; You should have received a copy of the GNU General Public License
  14. ;; along with ein-events.el. If not, see <http://www.gnu.org/licenses/>.
  15. ;;; Commentary:
  16. ;;
  17. ;;; Code:
  18. (eval-when-compile (require 'cl))
  19. (require 'eieio)
  20. (require 'ein-core)
  21. (require 'ein-log)
  22. ;;; Events handling class
  23. (defclass ein:events ()
  24. ((callbacks :initarg :callbacks :type hash-table
  25. :initform (make-hash-table :test 'eq)))
  26. "Event handler class.")
  27. (defun ein:events-new ()
  28. "Return a new event handler instance."
  29. (make-instance 'ein:events))
  30. (defun ein:events-trigger (events event-type &optional data)
  31. "Trigger EVENT-TYPE and let event handler EVENTS handle that event."
  32. (ein:log 'debug "Event: %S" event-type)
  33. (ein:aif (gethash event-type (oref events :callbacks))
  34. (mapc (lambda (cb-arg) (ein:funcall-packed cb-arg data)) it)
  35. (ein:log 'info "Unknown event: %S" event-type)))
  36. (defmethod ein:events-on ((events ein:events) event-type
  37. callback &optional arg)
  38. "Set event trigger hook.
  39. When EVENT-TYPE is triggered on the event handler EVENTS,
  40. CALLBACK is called. CALLBACK must take two arguments:
  41. ARG as the first argument and DATA, which is passed via
  42. `ein:events-trigger', as the second."
  43. (assert (symbolp event-type))
  44. (let* ((table (oref events :callbacks))
  45. (cbs (gethash event-type table)))
  46. (push (cons callback arg) cbs)
  47. (puthash event-type cbs table)))
  48. (provide 'ein-events)
  49. ;;; ein-events.el ends here