js设计模式--桥接模式

按GoF的定义,桥接模式的作用在于 “将抽象与其实现隔离开来,以便二者独立变化”;
常见的应用场景: JavaScript中的事件回调

示例:事件监听器
单击某个元素 去获取商品的信息;
实现方式如下:

addEvent(element,'click',getProductById);
function getProductById(e){
   var id = this.id;
   asyncRequest('GET','queryProduct.php?id='+ id , function(res){
   	console.log(res);
   })
}
//这个版本不利于单元测试并且不方便复用,getProductById方法 与上下文绑定 ,使用了this.id

改造版本:

addEvent(element,'click',getProByIdBridge);
function getProByIdBridge(e){
	getProductById(this.id,function(res){
		console.log(res);
	})
}
function getProductById(id,callback){
	asyncRequest('GET','queryProduct.php?id='+ id , function(res){
		callback(res);
	})
}
var asyncRequest = function(){
	function handleReadyState(o, callback){
		var pool = window.setInterval(function(){
			if(o $$ o.readyState == 4){
				window.clearInterval(pool);
				if(callback && typeof callback === 'function'){
					callback(o);
				}
			}
		},50);
	}
	
	var getXHR = function(){
		var http;
		try{
			http = new XMLHttpRequest();
			getXHR = function(){
				return new XMLHttpRequest();
			}
		}catch(e){
			var msxml = [
				'MSXML2.XMLHTTP.3.0',
				'MSXML2.XMLHTTP',
				'Mircosoft.XMLHTTP',
			];
			for(var i=0,len= msxml.length; i<len; i++){
				try{
					http = new ActiveXObject(msxml[i]);
					getXHR = function(){
						return new ActiveXObject(msxml[i]);
					}
					break;
				}catch(e){
					
				}
			}
		}
		return http;
	}
	
	return function(method, url, callback, postData){
		var http = getXHR();
		http.open(method, url, true);
		handleReadyState(http, callback);
		http.send(postData || null);
		return http;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值