react-class
Advanced tools
Comparing version
@@ -15,9 +15,17 @@ "use strict"; | ||
function autoBind(object){ | ||
function autoBind(object, filter){ | ||
var proto = object.constructor.prototype | ||
var names = Object.getOwnPropertyNames(proto).filter(function(key) { | ||
return skipMethods[key] !== 1 && typeof proto[key] === 'function' | ||
}) | ||
var filterFn = typeof filter == 'function' ? | ||
filter: | ||
filter && typeof filter == 'object' ? | ||
function(key) { | ||
return !filter[key] && skipMethods[key] !== 1 && typeof proto[key] === 'function' | ||
}: | ||
function(key) { | ||
return skipMethods[key] !== 1 && typeof proto[key] === 'function' | ||
} | ||
var names = Object.getOwnPropertyNames(proto).filter(filterFn) | ||
names.push('setState') | ||
@@ -24,0 +32,0 @@ names.forEach(function(key){ |
@@ -33,2 +33,4 @@ "use strict"; | ||
exports.autoBind = autoBind; | ||
exports.Component = ReactClass; | ||
exports.Component = ReactClass; | ||
module.exports = ReactClass; |
{ | ||
"name": "react-class", | ||
"version": "3.1.4", | ||
"version": "3.2.0", | ||
"description": "A carefully crafted base class for all your React components ", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
@@ -72,2 +72,9 @@ # react-class | ||
### autoBind filtering | ||
`autoBind` supports a second param, that can be used to filter what gets auto-binding or not. It can be a function or an object. | ||
* `autoBind(obj, filterFn)` - only those methods in `obj` are bound to the object for which the `filterFn` returns true | ||
* `autoBind(obj, skipObject)` - the methods whose names are found in the `skipObject` as truthy are skipped from autobinding. Eg: `autoBind(obj, { notBound: true, log: true })` will not bind the `obj.notBound` and `obj.log` methods to the `obj` object. | ||
## FAQ | ||
@@ -74,0 +81,0 @@ |
@@ -28,2 +28,48 @@ import test from 'ava' | ||
}) | ||
test('autoBind filter works', t => { | ||
class MyClass { | ||
constructor() { | ||
this.name = 'myclass' | ||
} | ||
returnThis() { | ||
return this || 0 | ||
} | ||
notBound() { | ||
return this || 1 | ||
} | ||
setState(){} | ||
} | ||
var obj = new MyClass() | ||
var unbound = autoBind(obj, { notBound: true }).notBound | ||
t.is( | ||
unbound(), | ||
1, | ||
'unbound' | ||
) | ||
var boundObj = autoBind(obj, function(name){ | ||
return name !== 'notBound' | ||
}) | ||
const returnThisBound = boundObj.returnThis | ||
const notBound = boundObj.notBound | ||
t.is( | ||
returnThisBound(), | ||
boundObj, | ||
'returnThisBound' | ||
) | ||
t.is( | ||
notBound(), | ||
1, | ||
'notBound' | ||
) | ||
}) |
19311
8.26%413
11.92%95
7.95%