Skip to content

Commit

Permalink
Don't autobind methods twice and remove deprecated call
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Dec 12, 2014
1 parent 8a3567a commit d1bf76a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
62 changes: 62 additions & 0 deletions modules/bindAutoBindMethods.js
@@ -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);
}
};
7 changes: 3 additions & 4 deletions modules/deepForceUpdate.js
@@ -1,15 +1,14 @@
'use strict';

var bindAutoBindMethods = require('./bindAutoBindMethods');

/**
* Updates a React component recursively, so even if children define funky
* `shouldComponentUpdate`, they are forced to re-render.
* Makes sure that any newly added methods are properly auto-bound.
*/
function deepForceUpdate(component) {
// ES6 classes won't have this
if (component._bindAutoBindMethods) {
component._bindAutoBindMethods();
}
bindAutoBindMethods(component);

if (component.forceUpdate) {
component.forceUpdate();
Expand Down

0 comments on commit d1bf76a

Please sign in to comment.