UNPKG

babel-autobind

Version:

it binds methods to its class prototype + Compatible with stub/spy used on unit-test frameworks (Sinon.Js, enzyme,...so on) + Can be integrated with 3rd party decorators (like @autobind decorator)

61 lines (48 loc) 2.46 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Autobind = Autobind; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function Autobind(Mocked, ClassName) { if (typeof Mocked === 'string') { return function (target) { return Autobind(target, Mocked); }; } var methods = Object.getOwnPropertyNames(Mocked.prototype); var getMethodProperty = function getMethodProperty(methodName, prop) { return Object.getOwnPropertyDescriptor(Mocked.prototype, methodName)[prop]; }; var methodsExcluded = ['constructor', 'render']; var ruleIncluder = function ruleIncluder(methodName) { return methodsExcluded.indexOf(methodName) < 0 && typeof getMethodProperty(methodName, 'value') === 'function'; }; var Mocker = function (_Mocked) { _inherits(Mocker, _Mocked); function Mocker() { _classCallCheck(this, Mocker); var _this = _possibleConstructorReturn(this, (Mocker.__proto__ || Object.getPrototypeOf(Mocker)).apply(this, arguments)); methods.filter(ruleIncluder).forEach(function (methodName) { _this[methodName] = _this[methodName].bind(_this); }); return _this; } return Mocker; }(Mocked); var rename = function () { Object.defineProperty(Mocker, 'name', { writable: true }); Mocker.name = ClassName || Mocked.name || 'AutoBoundComponent'; Object.defineProperty(Mocker, 'name', { writable: false }); }(); Object.keys(Mocked).forEach(function (staticAttribute) { Mocker[staticAttribute] = Mocked[staticAttribute]; }); return Mocker; };