diff --git a/README.md b/README.md index c69997d..ca8bda0 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ var line = d3.svg.line() ``` This is very common D3 callback code. Here is the same code with callbacks refactored -to use *d3-helpers* +with *d3-helpers* ```js var line = d3.svg.line() @@ -63,20 +63,21 @@ augmented by other tiny functions. First the *d3h* function itself Returns a function that can chain property access and function composition. -`d3h('propertyName', fnToApply, 'anotherPropertyName', orAnotherFn, ...);` +`d3h('propertyName', fnToApply, 'method name to call', 'anotherPropertyName', orAnotherFn, ...);` ```js var foo = { + getName: function() { return this.name; }, name: 'foo' }; function concatSelf(x) { return x + x; } function add2(x) { return x + 2; } -var f = d3h('name', concatSelf, 'length', add2); +var f = d3h('getName', concatSelf, 'length', add2); f(foo) // returns 8 // f is the same as function (obj) { - return add2(concatSelf(obj.name).length); + return add2(concatSelf(obj.getName()).length); } ``` @@ -88,6 +89,9 @@ Use on `d` argument: .(d3h.d('length', xScale)); ``` +When calling a method on the object, `this` is bound to the +object, and it is passed itself as first argument. + ### d3h.i Same chaining as `d3h.d` but operates on the second argument, usually the index diff --git a/bower.json b/bower.json index 98523e2..b8decb0 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "d3-helpers", "main": "index.js", - "version": "0.2.0", + "version": "0.2.1", "homepage": "https://github.com/bahmutov/d3-helpers", "license": "MIT", "ignore": [ diff --git a/index.js b/index.js index 53ed89e..57a0392 100644 --- a/index.js +++ b/index.js @@ -9,7 +9,11 @@ return function (d) { fns.forEach(function (fn) { if (typeof fn === 'string') { - d = d[fn]; + if (typeof d[fn] === 'function') { + d = d[fn].call(d, d); + } else { + d = d[fn]; + } } else if (typeof fn === 'function') { d = fn(d); } else { diff --git a/package.json b/package.json index 734c5b5..a910859 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "d3-helpers", "description": "Little utility D3 functions", - "version": "0.2.0", + "version": "0.2.1", "author": "Gleb Bahmutov ", "bugs": { "url": "https://github.com/bahmutov/d3-helpers/issues" diff --git a/test/helpers.spec.js b/test/helpers.spec.js index 40dffa5..da25ebd 100644 --- a/test/helpers.spec.js +++ b/test/helpers.spec.js @@ -35,6 +35,25 @@ describe('d3h d3-helpers', function () { } expect(explicit(foo)).to.equal(8); }); + + it('can call functions', function () { + var data = { + name: function () { + return 'foo'; + } + }; + expect(d3h('name')(data)).to.equal('foo'); + }); + + it('method, get property, execute function', function () { + var data = { + self: function () { + return this; + }, + age: 10 + }; + expect(d3h('self', 'age', add2)(data)).to.equal(12); + }); }); it('is a collection of functions', function () {