next up previous
Next: Controller Up: Implementation Previous: View

Model

Class ExampleModel is as simple as class ExampleView. As for ExampleView, it extends a base class of the MVC Infrastructure, class Model. The state is represented by a set of possible messages, as well as by the current message index. The current message index is also an observable property. A couple of methods are supplied in order to access the state.

 
from gtkmvc.model import Model

class ExampleModel (Model):
    """The model contains a set of messages
    and an observable property that represent the current message
    index"""

    # Observable property: code for that is automatically generated
    # by metaclass constructor. The controller will be the observer
    # for this property
    __properties__ = {
        "message_index" : -1 # -1 is the initial value
        }

    def __init__(self):
        Model.__init__(self)

        self.messages= ('Initial message',
                        'Another message', 
                        'A third message...',
                        'Model changed again')
        return

    def get_message(self, index): return self.messages[index]

    def set_next_message(self):
        # this changes the observable property:
        self.message_index = (self.message_index + 1) % len(self.messages)
        return

    pass # end of class

Notice the class' variable __properties__, which is a map of (property, value) couples. The base class Model belongs to a metaclass which automatically search for observalbe properties and generates the needed code to handle the notification. When the value of variable message_index changes, all registered observers will be notified.



Roberto Cavada 2004-11-16