美文网首页
原生js自定义事件

原生js自定义事件

作者: erichow | 来源:发表于2016-12-15 15:13 被阅读0次
    Array.prototype.forEach = Array.prototype.forEach || function(callback) {
      var arr = this;
      for (var i = 0, len = arr.length; i < len; i++) {
        callback(arr[i], i);
      }
    };
    
    Object.create = Object.create || function(proto) {
        function F() {}
        F.prototype = proto;
        return new F;
    }
    
    function Emitter() {
      this._events =   {};
    }
    
    Emitter.prototype.on = function(evtype, fn) {
      this._events[evtype] = this._events[evtype] || [];
      if (this._events[evtype].indexOf(fn) !== -1) return;
      this._events[evtype].push(fn);
    }
    Emitter.prototype.off = function(evtype, fn) {
      if (evtype in this._events === false)  return;
      fn && this._events[evtype].splice(this._events[evtype].indexOf(fn), 1);
      !fn && delete this._events[evtype];
    }
    Emitter.prototype.emit = function(evtype, detail) {
      var self = this;
      if (!(evtype in this._events)) return;
      this._events[evtype].forEach(function(fn, i) {
          fn.apply(self, detail);
      });
    }
    
    Emitter.eventify = function(Klass) {
        Klass.prototype = Object.create(Klass.prototype);
        for (var attr in Emitter.prototype) {
            Klass.prototype[attr] = Emitter.prototype[attr]
        }
        return Klass;
    }
    

    相关文章

      网友评论

          本文标题:原生js自定义事件

          本文链接:https://www.haomeiwen.com/subject/npfgmttx.html