All files / classes Dispatcher.ts

88.33% Statements 53/60
80.77% Branches 21/26
87.5% Functions 14/16
87.27% Lines 48/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169                        1x 3x   3x 3x 3x 3x                       14x         14x 1x 1x 2x   13x   13x 13x 22x   16x       16x                 14x                           12x     12x     1x 1x     11x 5x   5x 5x         5x     14x 5x     6x 10x   11x                     18x 18x 18x 18x   18x   10x 10x   10x 10x   10x       10x       18x                   3x 10x                   1x                       1x  
import { Dispatchable } from "../../interfaces";
 
export interface EventHandler {
  handler: Function;
  one?: boolean;
}
 
/*
 * Dispatcher constructor.
 *
 * @return {dispatcher} The new dispatcher instance.
 */
export default class Dispatcher implements Dispatchable {
  private handlers: { [key: string]: EventHandler[] } = {};
 
  constructor() {
    this.bind = this.bind.bind(this);
    this.unbind = this.unbind.bind(this);
    this.dispatchEvent = this.dispatchEvent.bind(this);
  }
 
  /**
   * Will execute the handler everytime that the indicated event (or the
   * indicated events) will be triggered.
   *
   * @param  {string}           events  The name of the event (or the events
   *                                    separated by spaces).
   * @param  {function(Object)} handler The handler to bind.
   * @return {dispatcher}               Returns the instance itself.
   */
  public bind(
    events: { [key: string]: Function } | string[] | string,
    handler?: Function
  ) {
    /* eslint-disable prefer-rest-params */
    if (arguments.length === 1 && typeof arguments[0] === "object") {
      const argObject = events;
      Object.keys(argObject).forEach(evts => {
        this.bind(evts, argObject[evts]);
      });
    } else Eif (arguments.length === 2 && typeof handler === "function") {
      const eventArray =
        typeof events === "string" ? events.split(" ") : events;
      eventArray
        .filter(e => !!e)
        .forEach(event => {
          Eif (!this.handlers[event]) this.handlers[event] = [];
 
          // Using an object instead of directly the handler will make possible
          // later to add flags
          this.handlers[event].push({
            handler
          });
        });
    } else
      throw new Error(
        `bind: Wrong arguments. eventstype=${typeof events} handlertype=${typeof handler}`
      );
 
    return this;
  }
 
  /**
   * Removes the handler from a specified event (or specified events).
   *
   * @param  {?string}           events  The name of the event (or the events
   *                                     separated by spaces). If undefined,
   *                                     then all handlers are removed.
   * @param  {?function(object)} handler The handler to unbind. If undefined,
   *                                     each handler bound to the event or the
   *                                     events will be removed.
   * @return {dispatcher}                Returns the instance itself.
   */
  public unbind(events?: string | string[], handler?: Function) {
    let i;
    let n;
    const eArray = typeof events === "string" ? events.split(" ") : events;
 
    if (!arguments.length) {
      Object.keys(this.handlers).forEach(key => delete this.handlers[key]);
      return this;
    }
 
    if (handler) {
      eArray.forEach(event => {
        if (this.handlers[event]) {
          const savedHandlers = [];
          this.handlers[event].forEach(h => {
            if (h.handler !== handler) {
              savedHandlers.push(h);
            }
          });
          this.handlers[event] = savedHandlers;
        }
 
        if (this.handlers[event] && this.handlers[event].length === 0)
          delete this.handlers[event];
      });
    } else
      for (i = 0, n = eArray.length; i !== n; i += 1)
        delete this.handlers[eArray[i]];
 
    return this;
  }
 
  /**
   * Executes each handler bound to the event
   *
   * @param  {string}     events The name of the event (or the events separated
   *                             by spaces).
   * @param  {?object}    data   The content of the event (optional).
   * @return {dispatcher}        Returns the instance itself.
   */
  public dispatchEvent(events: string | string[], data?: any) {
    const self = this;
    const eArray = typeof events === "string" ? events.split(" ") : events;
    data = data === undefined ? {} : data;
 
    eArray.forEach(eventName => {
      if (this.handlers[eventName]) {
        const event = self.getEvent(eventName, data);
        const savedHandlers = [];
 
        this.handlers[eventName].forEach(handler => {
          handler.handler(event);
          if (!handler.one) {
            savedHandlers.push(handler);
          }
        });
 
        this.handlers[eventName] = savedHandlers;
      }
    });
 
    return this;
  }
 
  /**
   * Return an event object.
   *
   * @param  {string}  events The name of the event.
   * @param  {?object} data   The content of the event (optional).
   * @return {object}         Returns the instance itself.
   */
  private getEvent = (event: string, data?: any) => {
    return {
      type: event,
      data: data || {},
      target: this
    };
  };
 
  /**
   * Augments an object with dispatching power
   */
  public static extend(target: any) {
    const instance = new Dispatcher();
    target.__dispatcher = instance;
    ["dispatchEvent", "bind", "unbind"].forEach(method => {
      if (target["method"]) {
        throw new Error(
          `dispatcher method ${method} is already defined on target`
        );
      }
      target[method] = instance[method];
    });
  }
}