Created
May 15, 2012 20:57
-
-
Save matbee-eth/2705093 to your computer and use it in GitHub Desktop.
Javascript method delayed chaining
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// var test = new API("Router.svc"); | |
// test.get().top(5).view("map"); | |
// It should execute() only when the last function has been called. | |
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.push(JSON.parse('{"'+method+'":"'+parameter+'"}')); | |
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: {} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment