Skip to content

Instantly share code, notes, and snippets.

@littlemerman
Created January 13, 2012 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save littlemerman/1609409 to your computer and use it in GitHub Desktop.
Save littlemerman/1609409 to your computer and use it in GitHub Desktop.
Roll you own API
// Allows the creation of an API from a base url and an array of objects with parameters and names.
var API = {};
API.init = function(baseUrl, parms) {
var o = {};
o.baseUrl = baseUrl;
o.parms = parms;
o.url = function() {
var r = [], i, len;
r.push(this.baseUrl);
r.push('/?');
for (i = 0, len = parms.length; i < len; i++) {
if (this.hasOwnProperty(this.parms[i].name)) {
r.push(this.parms[i].parameter);
r.push('=');
r.push(this[this.parms[i].name]);
r.push('&');
}
}
// Remove last ampersand
r.pop();
return r.join('');
};
return o;
};
var parameters = [
{
'name':'bid',
'parameter':'bid'
},
{
'name':'ask',
'parameter':'ask'
},
{
'name':'high',
'parameter':'high'
}
];
var yFinance = API.init('http://finance.yahoo.com', parameters);
yFinance.bid = 'bid';
yFinance.ask = 1;
$('#hello').text(yFinance.url());
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<p id="hello">Hello World</p>
</body>
</html>
@littlemerman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment