码迷,mamicode.com
首页 > Web开发 > 详细

nodejs事件机制

时间:2015-01-25 22:16:49      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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);
   }
};

 

nodejs事件机制

标签:

原文地址:http://www.cnblogs.com/zlz-ling/p/4248984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!