All files / src/utils pubsubUtil.js

0% Statements 0/21
0% Branches 0/12
0% Functions 0/4
0% Lines 0/21

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                                                                                                                             
/**
 * @description pubsub库
 * @author SoldierAb
 * @since 18-12-05
 */
 
 
class PubSub {
  constructor() {
    this.handlers = {};
  }
 
   on(type, listener) {    //添加事件
    if (!(type in this.handlers)) {
      this.handlers[type] = [];
    }
    this.handlers[type].push(listener);
  }
 
   off(type, listener) {   //解除事件
    let i,
      position = -1,
      list = this.handlers[type],
      length = this.handlers[type]?this.handlers[type].length:0;
 
    for (i = 0; i < length; i++) {
      if (list[i] === listener) {
        position = i;
        break;
      }
    }
 
    if (position === -1) {
      return;
    }
 
    if (length === 1) {
      delete this.handlers[type];
    } else {
      this.handlers[type].splice(position, 1);
    }
  }
 
   emit(type) {            //触发事件
    let args = Array.prototype.slice.call(arguments, 1),
      i,
      list = this.handlers[type],
      // length = this.handlers[type].length;
      length = this.handlers[type]?this.handlers[type].length:0;
 
 
    for (i = 0; i < length; i++) {
      list[i].apply(this, args);
    }
  }
 
}
 
 
 
export default PubSub;