auto-bind-js 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Alemzadeh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,154 @@
1
+ # auto-bind-js
2
+
3
+ > Automatically bind class methods to their instance. Zero dependencies.
4
+
5
+ A modern, feature-rich alternative to [`auto-bind`](https://www.npmjs.com/package/auto-bind) with extra capabilities: **lazy binding**, **regex pattern matching**, **decorators**, **Symbol-keyed methods**, and full **TypeScript** support.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install auto-bind-js
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Basic
16
+
17
+ ```js
18
+ import autoBind from 'auto-bind-js';
19
+
20
+ class Unicorn {
21
+ constructor(name) {
22
+ this.name = name;
23
+ autoBind(this);
24
+ }
25
+
26
+ message() {
27
+ return `${this.name} is awesome!`;
28
+ }
29
+ }
30
+
31
+ const unicorn = new Unicorn('Rainbow');
32
+ const { message } = unicorn;
33
+ message(); //=> 'Rainbow is awesome!'
34
+ ```
35
+
36
+ ### Bind specific methods (shorthand)
37
+
38
+ ```js
39
+ autoBind(this, 'handleClick', 'handleSubmit');
40
+ ```
41
+
42
+ ### Options
43
+
44
+ ```js
45
+ // Only bind these methods
46
+ autoBind(this, { include: ['handleClick', 'handleSubmit'] });
47
+
48
+ // Bind all except these
49
+ autoBind(this, { exclude: ['render', 'toString'] });
50
+
51
+ // Bind only methods matching a pattern
52
+ autoBind(this, { pattern: /^handle/ });
53
+
54
+ // Lazy binding — binds on first access (better perf for large classes)
55
+ autoBind(this, { lazy: true });
56
+ ```
57
+
58
+ ### React
59
+
60
+ Excludes all React lifecycle methods automatically:
61
+
62
+ ```js
63
+ import autoBindReact from 'auto-bind-js/react';
64
+
65
+ class MyComponent extends React.Component {
66
+ constructor(props) {
67
+ super(props);
68
+ autoBindReact(this);
69
+ }
70
+
71
+ handleClick() {
72
+ // `this` is always the component instance
73
+ }
74
+
75
+ render() {
76
+ return <button onClick={this.handleClick}>Click</button>;
77
+ }
78
+ }
79
+ ```
80
+
81
+ ### Decorators
82
+
83
+ ```js
84
+ import { boundClass, bound } from 'auto-bind-js/decorator';
85
+
86
+ // Class decorator — binds ALL methods
87
+ @boundClass
88
+ class Foo {
89
+ constructor() {
90
+ this.name = 'foo';
91
+ }
92
+
93
+ handleClick() {
94
+ return this.name; // always bound
95
+ }
96
+ }
97
+
98
+ // Method decorator — bind individual methods
99
+ class Bar {
100
+ constructor() {
101
+ this.name = 'bar';
102
+ }
103
+
104
+ @bound
105
+ handleClick() {
106
+ return this.name; // always bound
107
+ }
108
+ }
109
+ ```
110
+
111
+ ## API
112
+
113
+ ### `autoBind(self, options?)`
114
+
115
+ Bind methods of `self` to the instance. Returns `self`.
116
+
117
+ #### Options
118
+
119
+ | Option | Type | Description |
120
+ | --------- | ----------------- | -------------------------------------------- |
121
+ | `include` | `(string\|symbol)[]` | Only bind these methods |
122
+ | `exclude` | `(string\|symbol)[]` | Skip these methods |
123
+ | `pattern` | `RegExp` | Only bind methods whose names match this regex |
124
+ | `lazy` | `boolean` | Bind on first access instead of immediately |
125
+
126
+ ### `autoBindReact(self, options?)`
127
+
128
+ Same as `autoBind` but automatically excludes React lifecycle methods (`render`, `componentDidMount`, `shouldComponentUpdate`, etc.)
129
+
130
+ ### `boundClass(target)`
131
+
132
+ Class decorator. Auto-binds all methods when the class is instantiated.
133
+
134
+ ### `bound(target, key, descriptor)`
135
+
136
+ Method decorator. Lazily binds the decorated method to the instance on first access.
137
+
138
+ ## Features
139
+
140
+ - ✅ Zero dependencies
141
+ - ✅ Binds inherited methods
142
+ - ✅ Supports Symbol-keyed methods
143
+ - ✅ Include/exclude filters
144
+ - ✅ Regex pattern matching
145
+ - ✅ Lazy binding mode
146
+ - ✅ React lifecycle awareness
147
+ - ✅ Class & method decorators
148
+ - ✅ Full TypeScript declarations
149
+ - ✅ ESM + CommonJS dual package
150
+ - ✅ Lightweight (~2KB)
151
+
152
+ ## License
153
+
154
+ MIT
@@ -0,0 +1,6 @@
1
+ 'use strict';
2
+ const { boundClass, bound } = require('./index.cjs');
3
+ module.exports = boundClass;
4
+ module.exports.default = boundClass;
5
+ module.exports.boundClass = boundClass;
6
+ module.exports.bound = bound;
@@ -0,0 +1 @@
1
+ export { boundClass, bound, boundClass as default } from './index';
@@ -0,0 +1 @@
1
+ export { boundClass, bound, boundClass as default } from './index.mjs';
package/dist/index.cjs ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * auto-bind-js (CommonJS)
3
+ */
4
+
5
+ 'use strict';
6
+
7
+ const BUILTIN_OBJECT_METHODS = new Set([
8
+ 'constructor',
9
+ 'toString',
10
+ 'toLocaleString',
11
+ 'valueOf',
12
+ 'hasOwnProperty',
13
+ 'isPrototypeOf',
14
+ 'propertyIsEnumerable',
15
+ '__defineGetter__',
16
+ '__defineSetter__',
17
+ '__lookupGetter__',
18
+ '__lookupSetter__',
19
+ ]);
20
+
21
+ function getAllMethodNames(obj) {
22
+ const methods = new Set();
23
+ let proto = Object.getPrototypeOf(obj);
24
+
25
+ while (proto && proto !== Object.prototype) {
26
+ const keys = Object.getOwnPropertyNames(proto);
27
+ for (const key of keys) {
28
+ if (key === 'constructor') continue;
29
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
30
+ if (descriptor && typeof descriptor.value === 'function') {
31
+ methods.add(key);
32
+ }
33
+ }
34
+
35
+ const symbols = Object.getOwnPropertySymbols(proto);
36
+ for (const sym of symbols) {
37
+ const descriptor = Object.getOwnPropertyDescriptor(proto, sym);
38
+ if (descriptor && typeof descriptor.value === 'function') {
39
+ methods.add(sym);
40
+ }
41
+ }
42
+
43
+ proto = Object.getPrototypeOf(proto);
44
+ }
45
+
46
+ return methods;
47
+ }
48
+
49
+ function filterMethods(methods, options = {}) {
50
+ let filtered = [...methods];
51
+
52
+ filtered = filtered.filter((m) => typeof m === 'symbol' || !BUILTIN_OBJECT_METHODS.has(m));
53
+
54
+ if (options.include) {
55
+ const includeSet = new Set(options.include);
56
+ filtered = filtered.filter((m) => includeSet.has(m));
57
+ }
58
+
59
+ if (options.exclude) {
60
+ const excludeSet = new Set(options.exclude);
61
+ filtered = filtered.filter((m) => !excludeSet.has(m));
62
+ }
63
+
64
+ if (options.pattern) {
65
+ filtered = filtered.filter(
66
+ (m) => typeof m === 'string' && options.pattern.test(m)
67
+ );
68
+ }
69
+
70
+ return filtered;
71
+ }
72
+
73
+ function bindEager(self, methods) {
74
+ for (const method of methods) {
75
+ const val = self[method];
76
+ if (typeof val === 'function') {
77
+ Object.defineProperty(self, method, {
78
+ value: val.bind(self),
79
+ writable: true,
80
+ configurable: true,
81
+ enumerable: false,
82
+ });
83
+ }
84
+ }
85
+ }
86
+
87
+ function findDescriptorInChain(obj, key) {
88
+ let proto = Object.getPrototypeOf(obj);
89
+ while (proto && proto !== Object.prototype) {
90
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
91
+ if (desc) return desc;
92
+ proto = Object.getPrototypeOf(proto);
93
+ }
94
+ return undefined;
95
+ }
96
+
97
+ function bindLazy(self, methods) {
98
+ for (const method of methods) {
99
+ const proto = Object.getPrototypeOf(self);
100
+ const descriptor = Object.getOwnPropertyDescriptor(proto, method) ||
101
+ findDescriptorInChain(self, method);
102
+
103
+ if (!descriptor || typeof descriptor.value !== 'function') continue;
104
+
105
+ const originalFn = descriptor.value;
106
+
107
+ Object.defineProperty(self, method, {
108
+ configurable: true,
109
+ enumerable: false,
110
+ get() {
111
+ const boundFn = originalFn.bind(self);
112
+ Object.defineProperty(self, method, {
113
+ value: boundFn,
114
+ writable: true,
115
+ configurable: true,
116
+ enumerable: false,
117
+ });
118
+ return boundFn;
119
+ },
120
+ });
121
+ }
122
+ }
123
+
124
+ function autoBind(self, options) {
125
+ if (typeof options === 'string') {
126
+ const methodNames = [options, ...Array.from(arguments).slice(2)];
127
+ options = { include: methodNames };
128
+ }
129
+
130
+ const allMethods = getAllMethodNames(self);
131
+ const methods = filterMethods(allMethods, options);
132
+
133
+ if (options && options.lazy) {
134
+ bindLazy(self, methods);
135
+ } else {
136
+ bindEager(self, methods);
137
+ }
138
+
139
+ return self;
140
+ }
141
+
142
+ // React
143
+ const REACT_LIFECYCLE_METHODS = new Set([
144
+ 'render',
145
+ 'componentDidMount',
146
+ 'componentDidUpdate',
147
+ 'componentWillUnmount',
148
+ 'shouldComponentUpdate',
149
+ 'getSnapshotBeforeUpdate',
150
+ 'getDerivedStateFromProps',
151
+ 'getDerivedStateFromError',
152
+ 'componentDidCatch',
153
+ 'UNSAFE_componentWillMount',
154
+ 'UNSAFE_componentWillReceiveProps',
155
+ 'UNSAFE_componentWillUpdate',
156
+ 'getDefaultProps',
157
+ 'getInitialState',
158
+ 'componentWillMount',
159
+ 'componentWillReceiveProps',
160
+ 'componentWillUpdate',
161
+ ]);
162
+
163
+ function autoBindReact(self, options = {}) {
164
+ const exclude = [
165
+ ...(options.exclude || []),
166
+ ...REACT_LIFECYCLE_METHODS,
167
+ ];
168
+ return autoBind(self, { ...options, exclude });
169
+ }
170
+
171
+ // Decorators
172
+ function boundClass(target) {
173
+ const original = target;
174
+
175
+ const wrapped = function (...args) {
176
+ const instance = new original(...args);
177
+ autoBind(instance);
178
+ return instance;
179
+ };
180
+
181
+ wrapped.prototype = original.prototype;
182
+ Object.defineProperty(wrapped, 'name', { value: original.name });
183
+ Object.setPrototypeOf(wrapped, original);
184
+
185
+ for (const key of Object.getOwnPropertyNames(original)) {
186
+ if (['length', 'name', 'prototype', 'arguments', 'caller'].includes(key)) continue;
187
+ const desc = Object.getOwnPropertyDescriptor(original, key);
188
+ if (desc) Object.defineProperty(wrapped, key, desc);
189
+ }
190
+
191
+ return wrapped;
192
+ }
193
+
194
+ function bound(target, key, descriptor) {
195
+ if (!descriptor || typeof descriptor.value !== 'function') {
196
+ throw new TypeError('@bound can only be applied to methods');
197
+ }
198
+
199
+ const fn = descriptor.value;
200
+
201
+ return {
202
+ configurable: true,
203
+ enumerable: false,
204
+ get() {
205
+ if (this === target) {
206
+ return fn;
207
+ }
208
+
209
+ const boundFn = fn.bind(this);
210
+ Object.defineProperty(this, key, {
211
+ value: boundFn,
212
+ writable: true,
213
+ configurable: true,
214
+ enumerable: false,
215
+ });
216
+ return boundFn;
217
+ },
218
+ };
219
+ }
220
+
221
+ module.exports = autoBind;
222
+ module.exports.default = autoBind;
223
+ module.exports.autoBind = autoBind;
224
+ module.exports.autoBindReact = autoBindReact;
225
+ module.exports.boundClass = boundClass;
226
+ module.exports.bound = bound;
@@ -0,0 +1,80 @@
1
+ export interface AutoBindOptions {
2
+ /** Only bind these methods */
3
+ include?: (string | symbol)[];
4
+ /** Don't bind these methods */
5
+ exclude?: (string | symbol)[];
6
+ /** Only bind methods matching this regex */
7
+ pattern?: RegExp;
8
+ /** Use lazy binding (bind on first access via getter) */
9
+ lazy?: boolean;
10
+ }
11
+
12
+ /**
13
+ * Automatically bind all methods of an object to itself.
14
+ *
15
+ * @param self - The class instance (usually `this`)
16
+ * @param options - Configuration options
17
+ * @returns The instance (for chaining)
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * class MyClass {
22
+ * constructor() {
23
+ * autoBind(this);
24
+ * }
25
+ * myMethod() {
26
+ * return this;
27
+ * }
28
+ * }
29
+ * ```
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * // Shorthand: bind specific methods
34
+ * autoBind(this, 'method1', 'method2');
35
+ * ```
36
+ */
37
+ declare function autoBind<T extends object>(self: T, options?: AutoBindOptions): T;
38
+ declare function autoBind<T extends object>(self: T, ...methods: string[]): T;
39
+
40
+ /**
41
+ * React-aware autoBind. Automatically excludes React lifecycle methods.
42
+ *
43
+ * @param self - The React component instance
44
+ * @param options - Same options as autoBind
45
+ * @returns The instance
46
+ */
47
+ export declare function autoBindReact<T extends object>(self: T, options?: AutoBindOptions): T;
48
+
49
+ /**
50
+ * Class decorator that auto-binds all methods on instantiation.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * @boundClass
55
+ * class MyClass {
56
+ * handleClick() { ... }
57
+ * }
58
+ * ```
59
+ */
60
+ export declare function boundClass<T extends new (...args: any[]) => any>(target: T): T;
61
+
62
+ /**
63
+ * Method decorator that lazily binds the method to the instance.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * class MyClass {
68
+ * @bound
69
+ * handleClick() { ... }
70
+ * }
71
+ * ```
72
+ */
73
+ export declare function bound(
74
+ target: object,
75
+ key: string | symbol,
76
+ descriptor: PropertyDescriptor
77
+ ): PropertyDescriptor;
78
+
79
+ export default autoBind;
80
+ export { autoBind };
package/dist/index.mjs ADDED
@@ -0,0 +1,288 @@
1
+ /**
2
+ * auto-bind-js
3
+ * Automatically bind class methods to their instance.
4
+ *
5
+ * Features:
6
+ * - Bind all own and inherited prototype methods
7
+ * - Include/exclude specific methods
8
+ * - Regex pattern matching for method names
9
+ * - Lazy binding (bind on first access via getter)
10
+ * - React-aware variant (skips lifecycle methods)
11
+ * - Class & method decorator support
12
+ * - Full TypeScript support
13
+ * - Zero dependencies
14
+ */
15
+
16
+ const BUILTIN_OBJECT_METHODS = new Set([
17
+ 'constructor',
18
+ 'toString',
19
+ 'toLocaleString',
20
+ 'valueOf',
21
+ 'hasOwnProperty',
22
+ 'isPrototypeOf',
23
+ 'propertyIsEnumerable',
24
+ '__defineGetter__',
25
+ '__defineSetter__',
26
+ '__lookupGetter__',
27
+ '__lookupSetter__',
28
+ ]);
29
+
30
+ /**
31
+ * Get all method names from the prototype chain (excluding Object.prototype)
32
+ */
33
+ function getAllMethodNames(obj) {
34
+ const methods = new Set();
35
+ let proto = Object.getPrototypeOf(obj);
36
+
37
+ while (proto && proto !== Object.prototype) {
38
+ const keys = Object.getOwnPropertyNames(proto);
39
+ for (const key of keys) {
40
+ if (key === 'constructor') continue;
41
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
42
+ if (descriptor && typeof descriptor.value === 'function') {
43
+ methods.add(key);
44
+ }
45
+ }
46
+
47
+ // Also handle Symbol-keyed methods
48
+ const symbols = Object.getOwnPropertySymbols(proto);
49
+ for (const sym of symbols) {
50
+ const descriptor = Object.getOwnPropertyDescriptor(proto, sym);
51
+ if (descriptor && typeof descriptor.value === 'function') {
52
+ methods.add(sym);
53
+ }
54
+ }
55
+
56
+ proto = Object.getPrototypeOf(proto);
57
+ }
58
+
59
+ return methods;
60
+ }
61
+
62
+ /**
63
+ * Filter methods based on options
64
+ */
65
+ function filterMethods(methods, options = {}) {
66
+ let filtered = [...methods];
67
+
68
+ // Remove built-in object methods
69
+ filtered = filtered.filter((m) => typeof m === 'symbol' || !BUILTIN_OBJECT_METHODS.has(m));
70
+
71
+ // Include only specific methods
72
+ if (options.include) {
73
+ const includeSet = new Set(options.include);
74
+ filtered = filtered.filter((m) => includeSet.has(m));
75
+ }
76
+
77
+ // Exclude specific methods
78
+ if (options.exclude) {
79
+ const excludeSet = new Set(options.exclude);
80
+ filtered = filtered.filter((m) => !excludeSet.has(m));
81
+ }
82
+
83
+ // Match pattern
84
+ if (options.pattern) {
85
+ filtered = filtered.filter(
86
+ (m) => typeof m === 'string' && options.pattern.test(m)
87
+ );
88
+ }
89
+
90
+ return filtered;
91
+ }
92
+
93
+ /**
94
+ * Bind methods eagerly (standard mode)
95
+ */
96
+ function bindEager(self, methods) {
97
+ for (const method of methods) {
98
+ const val = self[method];
99
+ if (typeof val === 'function') {
100
+ Object.defineProperty(self, method, {
101
+ value: val.bind(self),
102
+ writable: true,
103
+ configurable: true,
104
+ enumerable: false,
105
+ });
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Bind methods lazily (bind on first access)
112
+ */
113
+ function bindLazy(self, methods) {
114
+ for (const method of methods) {
115
+ const proto = Object.getPrototypeOf(self);
116
+ const descriptor = Object.getOwnPropertyDescriptor(proto, method) ||
117
+ findDescriptorInChain(self, method);
118
+
119
+ if (!descriptor || typeof descriptor.value !== 'function') continue;
120
+
121
+ const originalFn = descriptor.value;
122
+
123
+ Object.defineProperty(self, method, {
124
+ configurable: true,
125
+ enumerable: false,
126
+ get() {
127
+ const boundFn = originalFn.bind(self);
128
+ // Replace getter with the bound value on first access
129
+ Object.defineProperty(self, method, {
130
+ value: boundFn,
131
+ writable: true,
132
+ configurable: true,
133
+ enumerable: false,
134
+ });
135
+ return boundFn;
136
+ },
137
+ });
138
+ }
139
+ }
140
+
141
+ function findDescriptorInChain(obj, key) {
142
+ let proto = Object.getPrototypeOf(obj);
143
+ while (proto && proto !== Object.prototype) {
144
+ const desc = Object.getOwnPropertyDescriptor(proto, key);
145
+ if (desc) return desc;
146
+ proto = Object.getPrototypeOf(proto);
147
+ }
148
+ return undefined;
149
+ }
150
+
151
+ /**
152
+ * Main autoBind function
153
+ *
154
+ * @param {object} self - The class instance (usually `this`)
155
+ * @param {object} [options] - Configuration options
156
+ * @param {string[]} [options.include] - Only bind these methods
157
+ * @param {string[]} [options.exclude] - Don't bind these methods
158
+ * @param {RegExp} [options.pattern] - Only bind methods matching this regex
159
+ * @param {boolean} [options.lazy] - Use lazy binding (bind on first access)
160
+ * @returns {object} The instance (for chaining)
161
+ */
162
+ function autoBind(self, options) {
163
+ // Support autoBind(this, 'method1', 'method2') shorthand
164
+ if (typeof options === 'string') {
165
+ const methodNames = [options, ...Array.from(arguments).slice(2)];
166
+ options = { include: methodNames };
167
+ }
168
+
169
+ const allMethods = getAllMethodNames(self);
170
+ const methods = filterMethods(allMethods, options);
171
+
172
+ if (options && options.lazy) {
173
+ bindLazy(self, methods);
174
+ } else {
175
+ bindEager(self, methods);
176
+ }
177
+
178
+ return self;
179
+ }
180
+
181
+ // ─── React-aware variant ────────────────────────────────────────────────────
182
+
183
+ const REACT_LIFECYCLE_METHODS = new Set([
184
+ 'render',
185
+ 'componentDidMount',
186
+ 'componentDidUpdate',
187
+ 'componentWillUnmount',
188
+ 'shouldComponentUpdate',
189
+ 'getSnapshotBeforeUpdate',
190
+ 'getDerivedStateFromProps',
191
+ 'getDerivedStateFromError',
192
+ 'componentDidCatch',
193
+ 'UNSAFE_componentWillMount',
194
+ 'UNSAFE_componentWillReceiveProps',
195
+ 'UNSAFE_componentWillUpdate',
196
+ 'getDefaultProps',
197
+ 'getInitialState',
198
+ 'componentWillMount',
199
+ 'componentWillReceiveProps',
200
+ 'componentWillUpdate',
201
+ ]);
202
+
203
+ /**
204
+ * React-aware autoBind. Skips React lifecycle methods.
205
+ *
206
+ * @param {object} self - The component instance
207
+ * @param {object} [options] - Same options as autoBind (exclude is merged)
208
+ * @returns {object} The instance
209
+ */
210
+ function autoBindReact(self, options = {}) {
211
+ const exclude = [
212
+ ...(options.exclude || []),
213
+ ...REACT_LIFECYCLE_METHODS,
214
+ ];
215
+ return autoBind(self, { ...options, exclude });
216
+ }
217
+
218
+ // ─── Decorator ──────────────────────────────────────────────────────────────
219
+
220
+ /**
221
+ * Class decorator: @boundClass
222
+ * Method decorator: @bound
223
+ *
224
+ * Usage:
225
+ * @boundClass
226
+ * class Foo { ... }
227
+ *
228
+ * class Foo {
229
+ * @bound
230
+ * handleClick() { ... }
231
+ * }
232
+ */
233
+ function boundClass(target) {
234
+ const original = target;
235
+
236
+ const wrapped = function (...args) {
237
+ const instance = new original(...args);
238
+ autoBind(instance);
239
+ return instance;
240
+ };
241
+
242
+ wrapped.prototype = original.prototype;
243
+ Object.defineProperty(wrapped, 'name', { value: original.name });
244
+ Object.setPrototypeOf(wrapped, original);
245
+
246
+ // Copy static properties
247
+ for (const key of Object.getOwnPropertyNames(original)) {
248
+ if (['length', 'name', 'prototype', 'arguments', 'caller'].includes(key)) continue;
249
+ const desc = Object.getOwnPropertyDescriptor(original, key);
250
+ if (desc) Object.defineProperty(wrapped, key, desc);
251
+ }
252
+
253
+ return wrapped;
254
+ }
255
+
256
+ /**
257
+ * Method decorator
258
+ */
259
+ function bound(target, key, descriptor) {
260
+ if (!descriptor || typeof descriptor.value !== 'function') {
261
+ throw new TypeError('@bound can only be applied to methods');
262
+ }
263
+
264
+ const fn = descriptor.value;
265
+
266
+ return {
267
+ configurable: true,
268
+ enumerable: false,
269
+ get() {
270
+ // Only define on the instance, not the prototype
271
+ if (this === target) {
272
+ return fn;
273
+ }
274
+
275
+ const boundFn = fn.bind(this);
276
+ Object.defineProperty(this, key, {
277
+ value: boundFn,
278
+ writable: true,
279
+ configurable: true,
280
+ enumerable: false,
281
+ });
282
+ return boundFn;
283
+ },
284
+ };
285
+ }
286
+
287
+ export default autoBind;
288
+ export { autoBind, autoBindReact, boundClass, bound };
package/dist/react.cjs ADDED
@@ -0,0 +1,5 @@
1
+ 'use strict';
2
+ const { autoBindReact } = require('./index.cjs');
3
+ module.exports = autoBindReact;
4
+ module.exports.default = autoBindReact;
5
+ module.exports.autoBindReact = autoBindReact;
@@ -0,0 +1,4 @@
1
+ import { AutoBindOptions } from './index';
2
+ declare function autoBindReact<T extends object>(self: T, options?: AutoBindOptions): T;
3
+ export default autoBindReact;
4
+ export { autoBindReact };
package/dist/react.mjs ADDED
@@ -0,0 +1 @@
1
+ export { autoBindReact as default, autoBindReact } from './index.mjs';
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "auto-bind-js",
3
+ "version": "1.0.0",
4
+ "description": "Automatically bind class methods to their instance. Supports include/exclude filters, decorator pattern, inheritance, and lazy binding.",
5
+ "author": "mohammad alemzadeh <alemzadeh.mohammad@outlook.com>",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.cjs",
13
+ "types": "./dist/index.d.ts"
14
+ },
15
+ "./react": {
16
+ "import": "./dist/react.mjs",
17
+ "require": "./dist/react.cjs",
18
+ "types": "./dist/react.d.ts"
19
+ },
20
+ "./decorator": {
21
+ "import": "./dist/decorator.mjs",
22
+ "require": "./dist/decorator.cjs",
23
+ "types": "./dist/decorator.d.ts"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "scripts": {
30
+ "build": "node build.js",
31
+ "test": "npx jest --no-cache",
32
+ "prepublishOnly": "npm run build && npm test"
33
+ },
34
+ "keywords": [
35
+ "auto-bind",
36
+ "autobind",
37
+ "bind",
38
+ "class",
39
+ "methods",
40
+ "this",
41
+ "context",
42
+ "react",
43
+ "decorator",
44
+ "prototype",
45
+ "es6",
46
+ "es2015"
47
+ ],
48
+ "license": "MIT",
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "https://github.com/MMDALEM/auto-bind-js"
52
+ },
53
+ "engines": {
54
+ "node": "22"
55
+ },
56
+ "devDependencies": {
57
+ "jest": "^30.2.0"
58
+ }
59
+ }