      1 pockets.EventTarget = Class.create({
      2   initialize: function() {
      3     this.eventHandlers_ = {};
      4   },
      5
      6   listen: function(eventType, eventHandler) {
      7     if (typeof this.eventHandlers_[eventType] == 'undefined') this.eventHandlers_[eventType] = [];
      8     var handlers = this.eventHandlers_[eventType] || [];
      9     if (handlers.indexOf(eventHandler) != -1) {
     10       throw new Error('Handler is already registered for event type: ' + eventType);
     11     }
     12     handlers.push(eventHandler);
     13   },
     14
     15   listenOnce: function(eventType, eventHandler) {
     16     var eventTarget = this;
     17     var wrappedEventHandler = function() {
     18       eventTarget.unlisten(eventType, wrappedEventHandler);
     19       eventHandler.apply(this, arguments);
     20     };
     21     this.listen(eventType, wrappedEventHandler);
     22   },
     23
     24   unlisten: function(eventType, eventHandler) {
     25     var handlers = this.eventHandlers_[eventType] || [];
     26     var index = handlers.indexOf(eventHandler);
     27     if (index == -1) {
     28       throw new Error('Handler does not exist for event type: ' + eventType);
     29     }
     30     handlers.splice(index, 1);
     31   },
     32
     33   stopListening: function() {
     34     for (var handler in this.eventHandlers_) {
     35       delete this.eventHandlers_[handler];
     36     }
     37   },
     38
     39   dispatch: function(eventType) {
     40     var extraArgs = $A(arguments);
     41     extraArgs.shift();
     42     var handlers = this.eventHandlers_[eventType] || [];
     43     for (var i = 0; i < handlers.length; i++) {
     44       try {
     45         handlers[i].apply(null, extraArgs);
     46       } catch(e) {
     47         Mojo.Log.error(e);
     48       }
     49     }
     50   }
     51 });