[plt-scheme] Dynamic menu-item% callback assignment?

From: Daniel Yoo (dyoo at cs.wpi.edu)
Date: Thu Feb 22 00:57:41 EST 2007

On Thu, 22 Feb 2007, Greg Johnston wrote:

> I'm using very modular MVC to create a GUI for a program. As such,
> it's not really possible to create the callbacks for menu-item%s when
> the objects are created. According to the MrEd manual, this is when
> callbacks are created, unfortunately.
> Is there any way to assign a callback later, or do I need to work around 
> this?

Hi Greg,

Yes; I have a small example of this in:


Here's the example:

(module sample-gui mzscheme
   (require (lib "mred.ss" "mred")
            (lib "class.ss")
            (lib "etc.ss"))

   (define view%
     (class frame%
       (init [label "test"])
       (super-new [label label])

       ;; The entry callback here does nothing until it's rewired
       ;; by the controller.
       (define (entry-callback text-field control-event)

       (define/public (set-entry-callback! f)
         (set! entry-callback f))

       (define entry-field
         (new text-field%
              [label "entry: "]
              [parent this]
              [callback (lambda args
                          (apply entry-callback args))]))
       (define result-field
         (new text-field%
              [label "result: "]
              [parent this]
              [enabled #f]))

       (define/public (get-entry-field)

       (define/public (get-result-field)

   (define controller%
     (class object%
       [init model]
       [init view]

       (define entry (send view get-entry-field))
       (define result (send view get-result-field))

       (define (entry-callback field event)
         (define (is-enter? event)
           (symbol=? 'text-field-enter
                     (send event get-event-type)))
         (when (is-enter? event)

       (define (update-result)
         (let* ([entry-str (send entry get-value)]
                [entry-num (string->number entry-str)])
           (cond [entry-num
                  (send result set-value
                        (number->string (model entry-num)))]
                  (send result set-value
                        (format "~a: not number" entry-str))])))

       (send view set-entry-callback! entry-callback)))

   (define (simple-squaring-gui)
     (let ([model (lambda (n) (* n n))]
           [view (new view% [label "Squares"])])
       (let ([controller (new controller%
                              [model model]
                              [view view])])
         (send view show #t)))))

Best of wishes!

Posted on the users mailing list.