Created
June 27, 2012 17:52
-
-
Save jbroadway/3005678 to your computer and use it in GitHub Desktop.
API wrapper example for use with Elefant's Restful class
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
// the api for accessing the site | |
var api = (function ($) { | |
var self = {}; | |
// the prefix for api requests | |
self.prefix = '/myapi/v1/'; | |
// enable/disable debugging output to the console | |
self.debug = false; | |
// helper function to verify parameters | |
var _has = function (obj, prop) { | |
return obj.hasOwnProperty (prop); | |
}; | |
// console log wrapper for debugging | |
var _log = function (obj) { | |
if (self.debug) { | |
console.log (obj); | |
} | |
return obj; | |
}; | |
// an api call to /myapi/v1/item/info | |
self.item_info (data, callback) { | |
// verify an id value has been passed | |
if (! _has (data, 'id')) { | |
throw new Error ('api.item_info() - Missing parameter: id'); | |
} | |
$.get ( | |
_log (self.prefix + 'item/info?id=' + data.id), | |
callback | |
); | |
return self; | |
}; | |
// a post api call to /myapi/v1/item/update | |
self.item_update (data, callback) { | |
// ...verify parameters... | |
$.post ( | |
_log (self.prefix + 'item/update'), | |
data, | |
callback | |
); | |
return self; | |
}; | |
return self; | |
})(jQuery); |
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
<script src="jquery.js"></script> | |
<script src="api.js"></script> | |
<script> | |
$(function () { | |
// call /myapi/v1/item/info | |
api.item_info ({id: 123}, function (res) { | |
if (! res.success) { | |
alert (res.error); | |
return; | |
} | |
// success! | |
console.log (res.data); | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment