jusbell
10/22/2013 - 1:14 PM

Angular Pub-sub service.

Angular Pub-sub service.

/**
 * @fileoverview Contains code for the logs pub-sub service.
 */
goog.provide('pantheon.logs.PubSubService');


/**
 * Creates a new pubsub service with the given scope as a communication
 * channel. It's recommended to use a new isolate scope created from the root
 * scope as the communication channel to avoid visiting every scope during the
 * angular digest cycle in the publishing phase.
 *
 * @param {!angular.Scope} scopeChannel
 * @constructor
 * @ngInject
 */
pantheon.logs.PubSubService = function(scopeChannel) {
    this.scope_ = scopeChannel;
};


/**
 * Publish an event
 * @param {string} eventId The event ID
 * @param {*=} data Event data
 */
pantheon.logs.PubSubService.prototype.publish = function(eventId, data) {
  this.scope_.$broadcast(eventId, data);
};


/**
 * Subscribe to an event
 * @param {!string} eventId The event ID
 * @param {!angular.Scope} scope The scope that will be listening for the event
 * @param {!Function} fn Subscriber callback function
 * @param {boolean=} subscribeOnce If true the subscriber callback function will
 * be removed after it has been called the first time.
 * @return {function()} The destroyer function which unregisters all listeners.
 */
pantheon.logs.PubSubService.prototype.subscribe = function(
    eventId, scope, fn, subscribeOnce) {
  var unsubscribeFn, unregisterDestoryFn, destroyFn;
  unsubscribeFn = this.scope_.$on(eventId, function($event, data) {
    // Make the $event parameter optional
    fn(data, $event);
    if (subscribeOnce) {
      destroyFn();
    }
  });
  unregisterDestoryFn = scope.$on('$destroy', unsubscribeFn);
  destroyFn = function() {
    unsubscribeFn();
    unregisterDestoryFn();
  };
  return destroyFn;
};