Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customize scope for arrow functions #679

Closed
wants to merge 4 commits into from

Conversation

theKashey
Copy link
Collaborator

Fixes #391 and (already closed) #242

@neoziro, this is the same idea, that I mentioned in your PR.

Problem – react-proxy instances ES5 classes with correct this, but cannot repeat the trick with ES6 classes, as result new Components will be created with their own contexts.
In other word - this in arrow function will target the real component, but one can use only the proxied one.

Solution - store pointer to the proxy context inside instance, and use it.

This PR does include just a change of babel plugin, to work normally it requires changes in react-proxy, but version 3, used by RHL is not public :(

The one, who wants repeat the trick - just copy-paste code to the createProxyClass.js

function linkInstance(instance, context){
  try {
    instance.__REACT_PROXY_CONTEXT = context.__REACT_PROXY_CONTEXT = context;
  } catch (err) {};
  return instance;
}

function proxyClass(InitialComponent) {
  // Prevent double wrapping.
  // Given a proxy class, return the existing proxy managing it.
  var existingProxy = findProxy(InitialComponent);
  if (existingProxy) {
    return existingProxy;
  }

  let CurrentComponent;
  let ProxyComponent;
  let savedDescriptors = {};

  function instantiate(factory, context, params) {
    const component = factory();

    try {
      return linkInstance(component.apply(context, params), context); // <----
    } catch (err) {
      // Native ES6 class instantiation
      const instance = new component(...params);

      Object.keys(instance).forEach(key => {
        if (RESERVED_STATICS.indexOf(key) > -1) {
          return;
        }
        context[key] = instance[key];
      });

      linkInstance(instance, context);  /// <-- not returning anything
    }
  }

Tested both in es5 and es6 environments – all green.

@theKashey
Copy link
Collaborator Author

Tests are dead without correct proxy.

@theKashey theKashey closed this Nov 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Invalid 'this' binding with async arrow function class properties
1 participant