wxpython之pubsub 發布-訂閱者模式

來源:互聯網
上載者:User

wxPython Pubsub 包提供的發布-訂閱模式,允許您的應用程式的不同部分之間發送資料。在許多情況下,使用發布-訂閱者模式,將大大簡化其設計複雜度和提高可測試性。羅賓 · 鄧恩,建立者的 wxPython,優雅的對Pubsub描述:

  基本上你的程式的一些組件訂閱特定的主題,然後其它組件發布該主題的訊息。

圖解:

 

Publisher基本用法:

pub.subscribe(listener, topic):listener訂閱者,這邊一般是函數。topic,uniqu的主題。

sendMessage(topic, data, onTopicNeverCreated):topic,uniqu的主題,data 要傳給訂閱者的資料。onTopicNeverCreated如果沒有這個主題被訂閱,應該有onTopicNeverCreated處理

例子:

#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name:        # Purpose:     ## Author:      ankier## Created:     12-01-2013# Copyright:   (c) ankier 2013# Licence:     <your licence>#-------------------------------------------------------------------------------from wx.lib.pubsub import Publisher as pubclass Student():    def __init__(self):        self.__Name = None                #註冊訂閱事件        pub.subscribe(self.__UpdateName,  'nameEvntTopic')        def SetName(self, name):        self.__Name = name         #訂閱事件        def __UpdateName(self, eventTopicData):        if self.__Name == 'NameA':            print 'You can not give me a new name as my name is ',self.__Name            return        else:            print 'I change name to ', eventTopicData.data        self.__Name = eventTopicData.data    stuA = Student()stuA.SetName('NameA')stuB = Student()stuB.SetName('NameB')#發布訊息pub.sendMessage('nameEvntTopic', ['NewName', 'Age'])#事件沒有被註冊時候,統一轉到該函數處理def onTopicNeverCreated(eventTopicData):    print eventTopicData#發布一個不存在的事件pub.sendMessage('NoneEvntTopic', ['NewName', 'Age'], onTopicNeverCreated)

運行結果:

You can not give me a new name as my name is  NameAI change name to  ['NewName', 'Age']('NoneEvntTopic',)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.