Version 0 of Custom event notification

Updated 2005-12-13 16:12:21 by lexfiend

lexfiend 13 Dec 2005: After noticing at least one request along the lines of "[event generate] without Tk", I decided to hack the following, which is almost-but-not-quite-like trigger:

  namespace eval notify {
    namespace export register deregister trigger
    array set narray {}

    proc register {name proc} {
      variable narray
      set narray(${name}_proc) $proc
      trace add variable narray($name) write ::notify::process_trigger
    }

    proc deregister {name} {
      variable narray
      if {[array names narray ${name}_proc] != ""} {
        trace remove variable narray($name) write ::notify::process_trigger
        array unset narray(${name}_proc)
        array unset narray(${name})
      }
    }

    proc process_trigger {narray name op} {
      after 1 [list eval $::notify::narray(${name}_proc) $::notify::narray(${name})]
    }

    proc trigger {name args} {
      variable narray
      set narray(${name}) $args
    }

  }

  proc test_print {arg1 args} {
    puts stderr "arg1 = $arg1"
    puts stderr "args = $args"
  }
  proc test_notify {} {
    notify::register !test1 test_print
    notify::trigger !test1 "This is" a test
    notify::trigger !test1 "This is" another test
    notify::deregister !test1
    notify::trigger !test1 "This should" not fire
  }
  after idle test_notify
  after 1000 {set ::forever 1}
  vwait forever

No warranties, and I'm sure it can be improved.

(As luck would have it, after I hacked the above up, I found The observer design pattern. Marco's implementation is certainly more elegant and can handle multiple registered procedures per trigger, but doesn't actually use the event queue as such.)