amwmedia
8/28/2014 - 12:49 PM

QuickChain

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>