tcl

Trace particular objects variable in Tcl (TclOO)


My question is: is it possible to trace variable of particular object? For example, I have 5 objects of the same class, and I need to check if particular variable in each object is changed and call particular procedure that is updated Tk widget that is corresponds to this particular object. I a little bit stuck because I know that we can add trace to global variable, but not sure how to trace variable inside particular object, especially if it could not exist until writing occurs. Thank you in advance, George.


Solution

  • The varname standard method (normally not exported, so typically only usable via my) should give you something you can use with trace or a Tk widget.

    oo::class create Example {
        variable xyz
        constructor {script} {
            trace add variable [my varname xyz] write $script
        }
        method test {} {
            set xyz 123
        }
    }
    
    Example create eg {apply {args {
        puts "Foo: $args"
    }}}
    eg test
    

    Note that in this specific case, you don't need varname because the trace resolves the variable name using local rules. But you would if you were using vwait or a Tk widget.


    A common related case is when you want to get the trace to call a (non-exported) method of the object. In that case, you make the trace callback with something like this:

    trace add variable $varName write [namespace code {my CallbackMethod}]
    

    Tcl 8.7/9.0 has a callback command to make that easier.

    trace add variable $varName write [callback CallbackMethod]