Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Don't autobind methods twice and remove deprecated call
- Loading branch information
Showing
2 changed files
with
65 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
'use strict'; | ||
|
||
/** | ||
* Based on https://github.com/facebook/react/blob/master/src/class/ReactClass.js#L637 | ||
*/ | ||
function bindAutoBindMethod(component, method) { | ||
var boundMethod = method.bind(component); | ||
|
||
boundMethod.__reactBoundContext = component; | ||
boundMethod.__reactBoundMethod = method; | ||
boundMethod.__reactBoundArguments = null; | ||
|
||
var componentName = component.constructor.displayName, | ||
_bind = boundMethod.bind; | ||
|
||
boundMethod.bind = function (newThis) { | ||
var args = Array.prototype.slice.call(arguments, 1); | ||
if (newThis !== component && newThis !== null) { | ||
console.warn( | ||
'bind(): React component methods may only be bound to the ' + | ||
'component instance. See ' + componentName | ||
); | ||
} else if (!args.length) { | ||
console.warn( | ||
'bind(): You are binding a component method to the component. ' + | ||
'React does this for you automatically in a high-performance ' + | ||
'way, so you can safely remove this call. See ' + componentName | ||
); | ||
return boundMethod; | ||
} | ||
|
||
var reboundMethod = _bind.apply(boundMethod, arguments); | ||
reboundMethod.__reactBoundContext = component; | ||
reboundMethod.__reactBoundMethod = method; | ||
reboundMethod.__reactBoundArguments = args; | ||
|
||
return reboundMethod; | ||
}; | ||
|
||
return boundMethod; | ||
} | ||
|
||
/** | ||
* Performs auto-binding similar to how React does it. | ||
* Skips already auto-bound methods. | ||
* Based on https://github.com/facebook/react/blob/master/src/class/ReactClass.js#L679. | ||
*/ | ||
module.exports = function bindAutoBindMethods(component) { | ||
for (var autoBindKey in component.__reactAutoBindMap) { | ||
if (!component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { | ||
continue; | ||
} | ||
|
||
if (component.hasOwnProperty(autoBindKey) && | ||
component[autoBindKey].__reactBoundContext === component) { | ||
continue; | ||
} | ||
|
||
var method = component.__reactAutoBindMap[autoBindKey]; | ||
component[autoBindKey] = bindAutoBindMethod(component, method); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters