javascript 自定义事件

function Emitter() {
}
Emitter.prototype = function() {
  var events = {};
  return {
    constructor: Emitter,
    on: function(type, cb) {
      var arr = events[type] = events[type] || [];
      (arr.indexOf(cb) === -1) && arr.push(cb);
      
      return this;
    },
    off: function(type, cb) {
      var arr = events[type] = events[type] || [], i = 0;
      while(arr.length !== i) {
        if (arr[i] === cb) {
          arr.splice(i, 1);
          break;
        }
        i++;
      }
      return this;
    },
    emitter: function(type) {
      var arr = events[type] = events[type] || [], i = 0;
      while(arr.length !== i) {
        arr[i].apply(this, [].slice.call(arguments, 1));
        i++;
      }
      return this;
    }
  }
}();
    原文作者:erichooooow
    原文地址: https://segmentfault.com/a/1190000004459532
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞