UNPKG

2.21 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var isFunction = require("lodash/isFunction");
4var factory_1 = require("./factory");
5var bind_1 = require("./bind");
6/**
7 * Binds methods of an object to the object itself, overwriting the existing method.
8 * @export
9 * @param {string[]} [methods=[]]
10 * @returns {ClassDecorator}
11 * @example
12 *
13 * @BindAll()
14 * class MyClass {
15 * bound() {
16 * return this;
17 * }
18 *
19 * unbound() {
20 * return this;
21 * }
22 * }
23 *
24 * const myClass = new MyClass();
25 *
26 * myClass.bound.call(null); // => MyClass {}
27 * myClass.unbound.call(null); // => MyClass {}
28 */
29function BindAll(methods) {
30 if (methods === void 0) { methods = []; }
31 return function (target) {
32 bindAllMethods(target, methods);
33 };
34}
35exports.BindAll = BindAll;
36exports.bindAll = BindAll;
37function bindAllMethods(target, methods) {
38 if (methods === void 0) { methods = []; }
39 var targetProto = target.prototype;
40 var proto = target.prototype;
41 var boundKeys = [];
42 while (proto && proto !== Object.prototype) {
43 for (var _i = 0, _a = Object.getOwnPropertyNames(proto); _i < _a.length; _i++) {
44 var key = _a[_i];
45 var include = methods.length ? methods.indexOf(key) !== -1 : true;
46 var descriptor = Object.getOwnPropertyDescriptor(proto, key);
47 if (include && key !== 'constructor') {
48 // If this property is a getter and it's NOT an instance decorated
49 // method, ignore it. Instance decorators are getters until first accessed.
50 if (descriptor.get) {
51 var chainData = factory_1.InstanceChainMap.get([proto, key]);
52 if (!chainData || !chainData.isMethod) {
53 continue;
54 }
55 }
56 if (isFunction(proto[key]) && boundKeys.indexOf(key) === -1) {
57 Object.defineProperty(targetProto, key, bind_1.Bind(proto, key, descriptor));
58 boundKeys.push(key);
59 }
60 }
61 }
62 proto = Object.getPrototypeOf(proto);
63 }
64}
65exports.default = BindAll;
66//# sourceMappingURL=bindAll.js.map
\No newline at end of file