• wxpython之pubsub 发布订阅者模式


    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 pub
    
    class 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  NameA
    I change name to  ['NewName', 'Age']
    ('NoneEvntTopic',)
  • 相关阅读:
    深入浅出Blazor webassembly之Local storage
    深入浅出Blazor webassembly之一种简单的部署方法
    深入浅出Blazor webassembly之以SubDirectory方式部署
    深入浅出Blazor webassembly之理解 Blazor WASM
    深入浅出Blazor webassembly之Logging
    [转]解决github不能访问的问题
    深入浅出Blazor webassembly之使用State container机制实现两组件联动
    深入浅出Blazor webassembly之使用EventCallback机制进行组件之间联动
    跳槽一年后的回顾
    Node.js躬行记(12)——BFF
  • 原文地址:https://www.cnblogs.com/ankier/p/2857648.html
Copyright © 2020-2023  润新知