Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Canvas And Its Callbacks In OO Code

DZone's Guide to

Canvas And Its Callbacks In OO Code

·
Free Resource
I learn to use 2 different types of Canvas callbacks
in the last snippet.

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.
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}