DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Canvas And Its Callbacks In OO Code

09.17.2005
| 3772 views |
  • submit to reddit
        I learn to use 2 different types of Canvas callbacks
in the <a href=http://www.bigbold.com/snippets/posts/show/730>last snippet</a>.

Typically, when I wrote a non-OO code, I will use
app.body = c = Canvas()
 where I already had 
from appuifw import *

The shortcoming is that I need to define callbacks first,
then pass it to the constructor
c = Canvas(redraw_callback, event_callback)
By using OO, the canvas is created in __init__() and it
can access other methods that come later in the code.
In this case, I use Canvas(self.update) which means that
the self.update will be used to redraw screen.

The secode way to use callback is Canvas.bind() method.
I have always been using this approach to binding any event
callback to a canvas. In some case, the event_callback in
the constructor maybe more elegant, though.

Notice my use of 
self.canvas.bind(EKeySelect, self.toggle)
Here I can bind the select key to self.toggle whose definition
will follow. This is more convenient than having to define
it first.  So, I think OO code is easier to write in this way.

I also use class variables instead of instance variables.
I found declaring it outside __init__() is more natural
and similar to my previous non-OO approach. 
(still easy to read, with variable & def declarations)
When I write self.myvar inside __init__(), I feel the code
is somewhat bloated. The class will have only 1 instance
anyway.