zoukankan      html  css  js  c++  java
  • nodejs事件机制

    var EventEmitter = function()  {
        this.evts = {};
    };
    EventEmitter.prototype = {
       constructor: EventEmitter,
       on: function(type, fn) {
           var evt = this.evts[type] || (this.evts[type] = []);
           if(evt.indexof(fn)) {
              evt.push(fn);
           }
       },
       off: function(type, fn) {
            var handlers = this.evts[type] || [], index;
            if(handlers.length === 0) {
               this.evts = {};
            } else if(arguments.length === 1) {
               delete this.evts[type];
            } else {
               handlers.some(function(f, idx) {
                  if(f === fn || f.fn === fn) {
                      index = idx;
                      return true;
                  }
               });
               index = handlers.indexof(fn);
               if(index > -1) {
                   handlers.splice(index, 1);
               }
               if(this.evts[type].length === 0) {
                  delete this.evts[type];
               }
            }
       },
       emit: function(type) {
          if(!this.evts[type])   return;
          var args = [].slice.call(arguments,1);
          this.evts[type].foreach(function(f) {
             f.apply(null,args);
          });
       },
       once: function(type, fn) {
          var self = this;
          var f = function() {
             fn.apply(this,[].slice.call(arguments,0));
             self.off(type, f);
          }
          f.fn = fn;
          this.on(type, f);
       }
    };
  • 相关阅读:
    主席树学习记录
    P1072 Hanson 的趣味题 题解
    好文章收集
    计算几何专题
    小问题
    CSP-S2020题解
    上下界网络流
    想到的无法解决的点子
    省选联考2020组合数问题
    省选数学复习
  • 原文地址:https://www.cnblogs.com/zlz-ling/p/4248984.html
Copyright © 2011-2022 走看看