Threaded View

  1. #1
    Sencha User
    Join Date
    Aug 2011
    Posts
    13
    Vote Rating
    0
    jonsykes is on a distinguished road

      0  

    Default Answered: Anonymous Topic Style Pub/Sub system?

    Answered: Anonymous Topic Style Pub/Sub system?


    Been poking around the code base, but I don't see anything obvious that fills this need.

    Does 4.x not have an anonymous pub/sub system in place?

    Something akin to dojo's publish/subscribe functionality

    http://davidwalsh.name/dojo-pub-sub

  2. It doesn't, but I whipped up a simple mechanism you could extend to your liking:

    Code:
    // Define
    
    
    Ext.define('PubSub', {
      extend: 'Ext.util.Observable',
    
    
      statics: {
        instance: null,
    
    
        subscribe: function (topic, listener, scope) {
          // Route messages through instance
          if (!PubSub.instance) {
            PubSub.instance = new this();
          }
    
    
          var inst = PubSub.instance;
    
    
          // Ensure that event is declared
          if (!inst.events[topic]) {
            inst.addEvents(topic);
          }
    
    
          // Then listen on it, with declared scope
          inst.mon(inst, topic, listener, scope || inst);
        },
    
    
        publish: function () {
          var inst = PubSub.instance;
          var args = Ext.Array.toArray(arguments);
          var topic = args[0];
    
    
          // If the topic has been declared through subscribe
          if (inst && topic && inst.events[topic]) {
            // A quirk in Observable requires me to lowercase the topic name
            // I could have used inst.fireEvent(topic, args.slice(1))
            // but the listener would get the args as a single array 
            // parameter in arguments[0].
            // This allows the published arguments to be passed properly.
           
            var evt = inst.events[topic.toLowerCase()];
            evt.fire.apply(evt, args.slice(1));
          }
        }
      }
    });
    
    
    // Subscribe
    
    
    PubSub.subscribe('testTopic', function (a, b) {
      alert(a + ' = ' + b);
    }, this);
    
    
    PubSub.subscribe('testTopic', function (a, b) {
      alert(a + ' != ' + b);
    }, this);
    
    
    // Publish
    
    
    PubSub.publish('testTopic', 'x', 5);
    Note - this is rudimentary - it doesn't have topic management (remove listeners and event declarations), but that could be added.

    hope this helps,

    stevil