[Egret]优雅的写http

首先,自从使用链式调用的写法后,就一发不可收拾的喜爱上了这种优雅的方式。不管是写架构还是写模块,我都会不自觉的使用这种最优雅的方式。链式写法既减少了代码量,又非常优雅的。

在使用 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);
        }
    }
}
posted @ 2017-01-02 10:48  richliu1023  阅读(2379)  评论(0编辑  收藏  举报