Permalink
Browse files

Adds ability to bind given functions.

  • Loading branch information...
1 parent f30b57e commit 7acc3a814e83b2f80f263ed2dee0fc0ee71a3e4f Chakrit Wichian committed May 17, 2013
Showing with 38 additions and 5 deletions.
  1. +12 −0 README.md
  2. +13 −5 lib/jam.js
  3. +13 −0 test/jam.js
View
@@ -91,6 +91,18 @@ code dependent on the number of arguments given.
Passing `next` as first argument eliminates the dependency since you can bind as many
arguments as you want and the `next()` is still passed as first argument always.
+Since this pattern allows you to pass functions verbatim, JAM also helps you binds the
+funciton context as well if you supply the context object as the second argument:
+
+```js
+var myObj =
+ { text: 'HELLO'
+ , echo: function() { console.log(this.text); }
+ };
+
+jam(myObj.echo, myObj); // executes myObj.echo with this === myObj
+```
+
Additionally, there are helpers available that lets you build JAM chains more easily.
# HELPERS
View
@@ -7,7 +7,7 @@ module.exports = (function() {
// # INTERNAL HELPERS
- // Helpers to work with `arguments`
+ // Function and arguments helpers.
var toArgs = function(args) { return Array.prototype.slice.call(args); };
function replaceHead(args, newHead) {
@@ -18,6 +18,10 @@ module.exports = (function() {
return args;
}
+ function bind(func, context) {
+ return function() { return func.apply(context, arguments); };
+ }
+
// Common assertions
function ensureFunc(func, argName) {
assert(typeof func === 'function', argName + ' argument missing or not a function');
@@ -172,7 +176,7 @@ module.exports = (function() {
// # JAM function
// Exported function starts the asynchronous call chain.
- function jam(func) {
+ function jam(func, context) {
ensureFunc(func, 'function');
var steps = [];
@@ -207,14 +211,18 @@ module.exports = (function() {
// Subsequent invocation of the function returned from the `jam` function simply adds
// the given function to the chain.
- function context(func) {
+ function continuable(func, context) {
ensureFunc(func, 'function');
+ if (context) { // TODO: Handle falsy things?
+ func = bind(func, context);
+ }
+
steps.push(func);
- return context;
+ return continuable;
};
- return includeHelpers(context(func));
+ return includeHelpers(continuable(func, context));
};
// ---
View
@@ -100,6 +100,19 @@
(done);
});
+ it('should calls initial function with `this` bound to supplied context object', function(done) {
+ this.jam(function(next) {
+ assert.equal(this, assert);
+ next()
+ }, assert)(done);
+ });
+
+ it('should calls chained function with `this` bound to supplied context object', function(done) {
+ this.jam(function(next) { next(); })
+ (function(next) { assert.equal(this, assert); next() }, assert)
+ (done);
+ });
+
}); // function
});

0 comments on commit 7acc3a8

Please sign in to comment.