UNPKG

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