我有一个可以接受某些参数的网络服务,例如 ?top=5&orderby=column --- 等等...
我希望能够像这样执行我的对象:
var call = new API();
call.get().top(5).skip(15).orderby("address");
挑战在于只有最后一个 orderby 触发 execute() 方法。这是我的代码。如果您有更好的想法,请告诉我!当前每个函数结束时延迟 25ms,并在下一个函数开始时停止计时器。这是适当的/可以接受的吗?
var API = function (webservice) {
this.webservice(webservice);
return this;
};
API.prototype = {
version: function (urlFormat) {
if (urlFormat) {
return "v" + urlFormat.split('.').join('_');
}
return sessionStorage.getItem("version");
},
path: function () {
return "../WebAPI/";
},
execute: function () {
var path = this.path() + this.webservice() + ".svc/";
if (this.__parameters) {
path += "?";
}
var first = true;
for (var k in this.__parameters) {
if (k !== "type")
path += ((first) ? (function(){first = false; return ""})() : "&") + "$" + k + "=" + this.__parameters[k];
};
console.log(this.__parameters.type + ": " + path);
return this;
},
put: function () {
this.doIt("type","put");
return this;
},
post: function () {
this.doIt("type","post");
return this;
},
get: function() {
this.doIt("type","get");
return this;
},
delete: function() {
this.doIt("type","delete");
return this;
},
toString: function () {
return "API";
},
webservice: function(webservice) {
if (webservice) {
this.__webservice = webservice;
}
else {
return this.__webservice;
}
},
top: function (p) {
this.doIt("top",p);
return this;
},
view: function (p) {
this.doIt("view",p);
return this;
},
orderby: function (p) {
this.doIt("orderby",p);
return this;
},
criteria: function (p) {
this.doIt("criteria",p);
return this;
},
skip: function (p) {
this.doIt("skip",p);
return this;
},
filter: function (p) {
this.doIt("filter",p);
return this;
},
doIt: function (method, parameter) {
this.__timerStop();
this.__parameters[method] = parameter;
this.__timerStart();
},
__timerStop: function () {
if (this.__timer) {
clearTimeout(this.__timer);
}
},
__timerStart: function (append) {
var self = this;
if (this.__timer) {
this.__timerStop();
}
this.__timer = setTimeout(function() {
console.log("executing.");
console.log(JSON.stringify(self.__parameters));
self.execute();
}, 25);
},
__parameters: {}
};