• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JavaScript Publish & Subscribe

    Blogs20142014-01-16


    1. Publish & Subscribe

    var PubSub = {
      subscribe: function(ev, callback) {
        //create this._callbacks object if not exist.
        var calls = this._callbacks || (this._callbacks = {});
    
        //create this._callbacks events array if not exist
        //add callback function to this._callbacks[ev]
        (this._callbacks[ev] || (this._callbacks[ev]=[])).push(callback);
    
        //return Pubsub
        return this;
      },
    
      publish: function() {
        console.log('publish:', arguments);
    
        // convert arguments to array, so can shift it.
        var args = Array.prototype.slice.call(arguments, 0);
    
        // get event name (first arg)
        var ev = args.shift();
    
        var list, calls, i, l;
    
        // this._callbacks is non object?
        if(!(calls = this._callbacks)) return this;
    
        // this._callbacks[ev] not exist?
        if(!(list  = this._callbacks[ev])) return this;
    
        // execute callback
        for(i=0, l=list.length; i<l; i++) {
            list[i].apply(this, args);
        }
        return this;
      }
    }
    //testing:
    PubSub.subscribe('event1', function() { console.log('callback 1'); });
    PubSub.subscribe('event2', function(val) { console.log('callback 2: ' + val); });
    PubSub.subscribe('event3', function(ary) { console.log('callback 3', ary); });
    
    PubSub.publish('event1');  //callback 1
    PubSub.publish('event2', 123);  //callback 2: 123
    PubSub.publish('event3', [1,2,3]); //callback 3 [1, 2, 3] 

    2. ().call(obj[i], i)

    An interesting example from Function.prototype.call():

    var animals = [
      {species: 'Lion', name: 'King'},
      {species: 'Whale', name: 'Fail'}
    ];
    #0 Lion: King VM14706:10
    #1 Whale: Fail
    for (var i = 0; i < animals.length; i++) {
      (function (i) {
        this.print = function () {
          console.log('#' + i  + ' ' + this.species
                      + ': ' + this.name);
        }
        this.print();
      }).call(animals[i], i);
    }
    #0 Lion: King VM14706:10
    #1 Whale: Fail 

    3. Tiny Pub/Sub

    (function($) {
      var o = $({});
    
      $.subscribe = function() {
        o.bind.apply(o, arguments);  //or on:
      };
    
      $.unsubscribe = function() {
        o.unbind.apply(o, arguments); //or off:
      };
    
      $.publish = function() {
        //['event2', 123]
        //var args = [].splice.call(arguments, 1,1);
        //args = [].splice.call(arguments, 0);
        //o.trigger.apply(o, args);
        o.trigger.apply(o, arguments);
      }
    })(jQuery);
    
    //testing:
    $.subscribe('topic', function(event, a,b,c) {
      console.log(event.type, b,c,a);
    });
    $.publish('topic', {a:'b'}, ['aa', 'bb', 'cc']);
    //'topic', aabbcc