Created
June 14, 2012 18:21
-
-
Save mendelgusmao/2931935 to your computer and use it in GitHub Desktop.
AJAX Fluent Interface
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
function AJAXFluentInterface(uri) { | |
this.uri = uri || ""; | |
this.retrieve = function(data, type) { | |
return $.ajax({ | |
type: type || "GET", | |
url: this.uri, | |
dataType: "json", | |
data: data | |
}) | |
}; | |
this.registerEndpoint = function(endpoint, methods) { | |
if (endpoint == "") { | |
return; | |
} | |
var splittedEndpoint = endpoint.split("/"); | |
methods = methods || ["GET"]; | |
if (splittedEndpoint[0] == "") { | |
splittedEndpoint.splice(0, 1); | |
} | |
var part = splittedEndpoint[0]; | |
if (this[part] === undefined) { | |
this[part] = new AJAXFluentInterface([this.uri, part].join("/")); | |
} | |
for (i in methods) { | |
this[part][methods[i].toLowerCase()] = function(data) { | |
return this.retrieve(data, methods[i]); | |
} | |
} | |
splittedEndpoint.splice(0, 1); | |
this[part].registerEndpoint(splittedEndpoint.join("/"), methods); | |
}; | |
this.compile = function() { | |
/* TODO | |
Concept: | |
registerEndpoint("/foo/bar") | |
-> .foo.bar == .foo.bar.get | |
*/ | |
} | |
} | |
application = new AJAXFluentInterface(); | |
application.registerEndpoint("/auth/Login", ["POST"]); | |
application.registerEndpoint("/auth/Logout"); | |
application.registerEndpoint("/auth/foo/bar/baz/xpto/ximbica"); | |
console.log(application); | |
console.log(application.auth.uri); | |
console.log(application.auth.Login.uri); | |
console.log(application.auth.Logout.uri); | |
console.log(application.auth.foo.bar.baz.xpto.ximbica.uri); | |
application.auth.Login.post({username: "admin", password: "admin"}).done(function(e) { | |
console.log(e); | |
}); | |
application.auth.Logout.get().done(function(e) { | |
console.log(e); | |
}); | |
application.auth.get().done(function(e) { | |
console.log(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment