I've like to expose a fluent service API similar to that on the AngularJS $http API while delegating to it.
Something like:
login(user).success(function(data, status) {
// success case
}).error(function(data, status) {
// fail case
}).go();
The implementation would actually somehow invoke the AngularJS $http API.
$http.post('/api/login', user).success(function(data, status) {
// success case
}).error(function(data, status) {
// fail case
});
Any pointers would be greatly appreciated.
The secret is as simple as returning this
for each chainable method call:
var MyApi = {
something : function() {
console.log('something');
return this;
},
elseIsh : function() {
console.log('else');
return this;
},
again : function() {
console.log('again');
return this;
}
}
MyApi.something().again().elseIsh().again();
And with an initial function call with a new constructor function like this:
var does = function() {
if(this.constructor !== does) {
return new does();
}
console.log('does');
}
does.prototype.something = function() {
console.log('something');
return this;
}
does.prototype.elseIsh = function() {
console.log('else');
return this;
}
does.prototype.again = function() {
console.log('again');
return this;
}
does().again().something().elseIsh().again();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.