一段javascript设计模式应用场景

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=">
<title>test </title>
</head>
<body>
<script> 
(function(window){

		function comets(url){
				if (!url || typeof url != 'string')
				{
					return;
				}
			   
				var Client = function(url) {
					var self = this; 
					this.events = []; 
					this.onmessage = function(e){
					console.log('此时如果Client.onmessage 被执行 Client.events属性中就是 function(data){ for (var i  = 0; i < fs.length; i++) {'+
							   'fs[i](data.parseJSON(), data);}  } 这里fs会去找');
						var es = this.events;
						for (var i = 0; i < es.length; i++)
						{
							es[i](11111, 'hello world');  //es[i] 相当于A函数  
						}
					}
				 
				//绑定推送事件
					this.bind = function(handle) {
						if (typeof handle != 'function') 
						{
							return this;
						}
						
						this.events.push(handle);
						console.log('--------client对象中的bind()方法将 传过来的参数 追加到 Client.events属性');
						return this;
					}
					 
					setInterval(function() { self.onmessage();}, 2000);
				}
				
				return new Client(url);
		}

	
	
	
	 var _ = {};
	 /*推送模块*/
	 _.comet = {
		_funcs : [],  //不断往此数组追加函数
		init : function(){
			var fs = this._funcs;
			 console.log('_.comet.init() 函数被执行  comets函数被执行,并实例化它内部的client对象返回  client对象中的bind()方法被执行');
			var url ='bixin.beta.golds-cloud.com?channel_id=r1000';
			comets(url).bind(function(a, b){
				   for (var i  = 0; i < fs.length; i++)
				   {
					   fs[i](a, b); 	//执行_funcs中的元素(追加的函数)
				   }
			   });
		},
		bind : function(func){
			if (typeof func != 'function')
			{
				return false;
			}
			this._funcs.push(func);	//不断的将方法 追加进_funcs数组中
			 console.log('_.comet.bind()函数已经将传过来的 函数 作为参数追加到了_.comet._funcs数组中');
		}
	 }
	
	_.chat = {
	    time: new Date(),
		init:function(){
		     console.log('_.chat.init()函数已经被执行');
		        _.comet.bind(function(j, d){  console.log(j +"  -第一种方式打印-  "+ d);});  	

               _.comet.bind(function(j, d){  console.log(j +"  -第二种方式打印-  "+ d);});		

               _.comet.bind(function(j, d){  console.log(j +"  -第二种方式打印-  "+ d);});					   
	    }
	};
	 
	 _.init = function() {
	        _.comet.init();
	        _.chat.init();
	 };
	 window.HD = _;
  })(window);

  //执行
  HD.init();
</script>
</body>
</html>

 

posted @ 2016-02-20 12:24  诗兄  阅读(418)  评论(0编辑  收藏  举报