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

4.js模式-发布-订阅模式

时间:2015-10-11 19:20:29      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

1. 发布-订阅模式

var observe = (function(){

      var events = {},

             listen,

             trigger,

             remmove;

     

      listen = function(key,fn){

             if(!events[key]){

                    events[key] = [];

             }

            

             events[key].push(fn);

      };

     

      trigger = function(){

             var key = Array.prototype.shift.call(arguments);

             var fns = events[key];

             if(!fns || fns.length === 0){

                    return false;

             }

            

             for(var i=0,fn;fn=fns[i++];){

                    fn.apply(this,arguments);

             }

      };

     

      remove = function(key,fn){

             var fns = events[key];

             if(!fns){

                    return false;

             }

             if(!fn){

                    fns && (fns.length=0);

             }else{

                    for(var l =fns.length -1;l>=0;l--){

                           var _fn = fns[l];

                           if(_fn===fn){

                                  fns.splice(l,1);

                           }

                    }

             }

      };

     

      return {

             listen:listen,

             trigger:trigger,

             remove:remove

      }

})();

 

  • observe.listen(‘xx‘,function(price){

      console.log(price);

});

 

observe.trigger(‘xx‘,2000);

4.js模式-发布-订阅模式

标签:

原文地址:http://www.cnblogs.com/SLchuck/p/4869713.html

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