首先,自從使用鏈式調用的寫法后,就一發不可收拾的喜愛上了這種優雅的方式。不管是寫架構還是寫模塊,我都會不自覺的使用這種最優雅的方式。鏈式寫法既減少了代碼量,又非常優雅的。
在使用 egret 的http請求時,發現代碼量很大,而且比較繁瑣,不能每次都要寫這么多的代碼吧……那來看看正常的寫法是什么:
getTest(): void {
//一點也不優雅
var loader: egret.URLLoader = new egret.URLLoader();
loader.dataFormat = egret.URLLoaderDataFormat.TEXT;
var req = new egret.URLRequest();
req.url = 'http://httpbin.org/user-agent';
var variables = new egret.URLVariables();
variables.decode('v=123');
variables.decode('s=123');
loader.data = variables;
loader.addEventListener(egret.Event.COMPLETE, this.onComplete, this);
loader.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onLoadError, this);
loader.load(req);
}
onComplete(e: egret.Event): void {
var loader = <egret.URLLoader>e.target;
console.log(loader.data);
}
onLoadError(): void {
console.log('error');
}
如何?每一次請求都有成功處理和失敗處理,又有參數要附帶,這樣寫估計會難受死了。
來看看我現在的寫法:
getTest(): void {
//這里很優雅
rm.Http.create()
.success(this.onSuccess, this)
.error(this.onLoadError, this)
.add('v=123')
.add('s=123')
.dataFormat(egret.URLLoaderDataFormat.TEXT)
.get('http://httpbin.org/user-agent');//也可以是post方法
}
onLoadError(): void {
console.log('error');
}
onSuccess(data): void {
console.log(data);
}
如何?是不是會很優雅,代碼量少了N多,而且每個http請求都可以這樣使用。😀
不賣關子,直接上鏈式的封裝類:
module rm {
export class Http {
private loader: egret.URLLoader = new egret.URLLoader();
private variables: egret.URLVariables;
static create(): Http {
return new Http();
}
success(handle: Function, thisObj: any = null): Http {
this.loader.addEventListener(egret.Event.COMPLETE, function (e: egret.Event): void {
var loader = <egret.URLLoader>e.target;
handle.call(thisObj, loader.data);
}, thisObj);
return this;
}
error(handle: Function, thisObj: any = null): Http {
this.loader.addEventListener(egret.IOErrorEvent.IO_ERROR, handle, thisObj);
return this;
}
add(source): Http {
if (!this.variables) {
this.variables = new egret.URLVariables();
}
this.variables.decode(source);
return this;
}
dataFormat(dataFormat: string): Http {
this.loader.dataFormat = dataFormat;
return this;
}
get(url: string) {
var req = new egret.URLRequest(url);
this.variables && (req.data = this.variables);
this.loader.load(req);
}
post(url: string) {
var req = new egret.URLRequest(url);
req.method = egret.URLRequestMethod.POST;
this.variables && (req.data = this.variables);
this.loader.load(req);
}
}
}