index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = function (_ref) {
  4. var t = _ref.types;
  5. function getTempId(scope) {
  6. var id = scope.path.getData("functionBind");
  7. if (id) return id;
  8. id = scope.generateDeclaredUidIdentifier("context");
  9. return scope.path.setData("functionBind", id);
  10. }
  11. function getStaticContext(bind, scope) {
  12. var object = bind.object || bind.callee.object;
  13. return scope.isStatic(object) && object;
  14. }
  15. function inferBindContext(bind, scope) {
  16. var staticContext = getStaticContext(bind, scope);
  17. if (staticContext) return staticContext;
  18. var tempId = getTempId(scope);
  19. if (bind.object) {
  20. bind.callee = t.sequenceExpression([t.assignmentExpression("=", tempId, bind.object), bind.callee]);
  21. } else {
  22. bind.callee.object = t.assignmentExpression("=", tempId, bind.callee.object);
  23. }
  24. return tempId;
  25. }
  26. return {
  27. inherits: require("babel-plugin-syntax-function-bind"),
  28. visitor: {
  29. CallExpression: function CallExpression(_ref2) {
  30. var node = _ref2.node,
  31. scope = _ref2.scope;
  32. var bind = node.callee;
  33. if (!t.isBindExpression(bind)) return;
  34. var context = inferBindContext(bind, scope);
  35. node.callee = t.memberExpression(bind.callee, t.identifier("call"));
  36. node.arguments.unshift(context);
  37. },
  38. BindExpression: function BindExpression(path) {
  39. var node = path.node,
  40. scope = path.scope;
  41. var context = inferBindContext(node, scope);
  42. path.replaceWith(t.callExpression(t.memberExpression(node.callee, t.identifier("bind")), [context]));
  43. }
  44. }
  45. };
  46. };
  47. module.exports = exports["default"];