Skip to content

Instantly share code, notes, and snippets.

@amwmedia
Last active August 29, 2015 14:05
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 amwmedia/ddaf997e76f87a124e0d to your computer and use it in GitHub Desktop.
Save amwmedia/ddaf997e76f87a124e0d to your computer and use it in GitHub Desktop.
QuickChain
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="QuickChain" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<meta charset="utf-8">
<title>QuickChain</title>
<style id="jsbin-css">
h1 {
position: relative;
}
</style>
</head>
<body>
<h1>hello there</h1>
<script id="jsbin-javascript">
console.clear();
// with this method you can call chainable functions multiple times by simply adding parens with more options
// to switch to another chainable function you use ._ or you can specify your own prop ($ in this case)
// this method SHOULD work for all chainable objects, not just with jquery
var h1 = quickChain($('h1'), '$');
h1.animate({left: 50})({top: 100}).$.css('color', 'red');
h1.text('yo!');
console.log(h1.text());
// ============================= //
// ====== QuickChain code ====== //
function quickChain(obj, escVal) {
escVal = escVal || '_';
function chain() {
var newChain = this, k;
function chainHook(f) {
function link() {
var rVal;
rVal = obj[f].apply(obj, arguments);
return rVal === obj ? link : rVal;
}
link[escVal] = newChain;
return link;
}
for (k in obj) {
if (typeof obj[k] === 'function') {
newChain[k] = chainHook(k);
}
}
}
chain.prototype = obj;
return new chain();
}
// ----------------------------- //
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment