2023-07-27 05:31:52 +00:00
|
|
|
/*
|
2024-02-13 15:59:27 +00:00
|
|
|
* SPDX-FileCopyrightText: syuilo and misskey-project
|
2023-07-27 05:31:52 +00:00
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-12-04 06:03:09 +00:00
|
|
|
// https://github.com/andreypopp/autobind-decorator
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return a descriptor removing the value and returning a getter
|
|
|
|
* The getter will return a .bind version of the function
|
|
|
|
* and memoize the result against a symbol on the instance
|
|
|
|
*/
|
2024-09-15 08:43:24 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2023-02-09 01:50:53 +00:00
|
|
|
export function bindThis(target: any, key: string, descriptor: any) {
|
2024-09-15 08:43:24 +00:00
|
|
|
const fn = descriptor.value;
|
2022-12-04 06:03:09 +00:00
|
|
|
|
|
|
|
if (typeof fn !== 'function') {
|
|
|
|
throw new TypeError(`@bindThis decorator can only be applied to methods not: ${typeof fn}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
configurable: true,
|
|
|
|
get() {
|
|
|
|
// eslint-disable-next-line no-prototype-builtins
|
2024-09-15 08:43:24 +00:00
|
|
|
if (this === target.prototype || this.hasOwnProperty(key)) {
|
2022-12-04 06:03:09 +00:00
|
|
|
return fn;
|
|
|
|
}
|
|
|
|
|
|
|
|
const boundFn = fn.bind(this);
|
2024-09-15 08:43:24 +00:00
|
|
|
Reflect.defineProperty(this, key, {
|
|
|
|
value: boundFn,
|
2022-12-04 06:03:09 +00:00
|
|
|
configurable: true,
|
2024-09-15 08:43:24 +00:00
|
|
|
writable: true,
|
2022-12-04 06:03:09 +00:00
|
|
|
});
|
2024-09-15 08:43:24 +00:00
|
|
|
|
2022-12-04 06:03:09 +00:00
|
|
|
return boundFn;
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|